将未修改的数据结构传递给二进制节点子代

问题描述

我有一个 iteration 问题,我有一个二叉树,我需要有一个由节点更新的HashMap,这个确切的映射应该对它的两个孩子都可以访问,这反过来将对其进行更新并将其提供给他们的孩子。基本上,左节点更新对右节点不可见,反之亦然。

使用递归可以做到这一点,方法是在开始时更新地图,将其传递给子代,然后在递归结束时重新更新/还原地图。

我该怎么做呢?

当然,我可以使用一堆HashMap,并适当地推送和弹出。但这涉及到一次又一次地复制此HashMap。有没有更好/更好的方法来做到这一点? 这是我的代码

public void iterativeUpdate(Node root) {
    
    Stack<Node<Integer>> nodesstack = new Stack<>(); 
    nodesstack.push(this.root);
    
    Stack<HashMap<Integer,Integer>> kvmapStack = new Stack<>();
    HashMap<Integer,Integer> map = new HashMap<>(); 
    kvmapStack.push(map);

    while (!nodesstack.isEmpty()) {
        Node<Integer> n = nodesstack.pop();
        HashMap<Integer,Integer> map = kvmapStack.pop();
        map.put(calculateKey(n.data),calculateValue(n.data));
        
        if (n.left != null) {
            nodesstack.push(n.left);
            HashMap<Integer,Integer> leftMap = new HashMap<>();
            leftMap.putAll(map);  
            kvmapStack.push(leftMap);
        }
        
        if (n.right != null) {
            nodesstack.push(n.right);
            HashMap<Integer,Integer> rightMap = new HashMap<>();
            rightMap.putAll(map);
            kvmapStack.push(rightMap);
        }
        
    }

}

private void calculateKey(int i) { ... }
private void calculateValue(int i) { ... }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)