二叉树节点编辑功能的问题



我的代码遇到了一些问题。

此函数的目的是遍历二叉树并对其进行编辑,以便从某个点开始的分支被位于"newNode"下的新分支替换。目前,它为它开始的树返回相同的值(因此current = newNode实际上不会编辑原始树(。

谁能解释为什么会这样?谢谢。

 public static Node editTree(Node current, Node newNode, String value) {
        if (current == null) {
            return null;
        }
        if (current.value.equals(value)) {
            current = newNode;
            return current;
        }
        if (!current.isLeaf()) {
            editTree(current.getLeft(), newNode, value);
            editTree(current.getRight(), newNode, value);
            return current;
        }
        return current;
    }

这必须以这样一种方式完成:首先遍历一棵树(原始树(,直到找到某个值。然后,容纳该值的节点将完全替换为一个新节点,该节点包含自己的值及其自己的左右节点。然后将全局变量 Node 设置为等于新编辑的树的值,然后用于重置原始树值。无法以任何其他方式完成的原因是因为我无法在节点类中设置左右节点的值,因为这是不允许的。

在第 current = newNode; 行中,您只是更改方法中 current 变量的引用。它不会影响原始树。您需要将newNode设置为对上一个节点的value

有关更多信息,请参阅 Java 是"按引用传递"还是"按值传递"?

将新值分配给current在方法之外将不起作用。我认为你应该使用返回值:

public static Node editTree(Node current, Node newNode, String value) {
        if (current == null) {
            return null;
        }
        if (current.value.equals(value)) {
            return newNode;
        }
        if (!current.isLeaf()) {
            current.setLeft(editTree(current.getLeft(), newNode, value));
            current.setRight(editTree(current.getRight(), newNode, value));
        }
        return current;
    }

更新:完整的代码和测试结果

public class Node {
    public final String value;
    private Node left;
    private Node right;
    Node(String value, Node left, Node right) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
    public Node getLeft() {
        return left;
    }
    public void setLeft(Node left) {
        this.left = left;
    }
    public Node getRight() {
        return right;
    }
    public void setRight(Node right) {
        this.right = right;
    }
    public boolean isLeaf() {
        return left == null && right == null;
    }
    @Override
    public String toString() {
        return "Node{" + "value=" + value + ", left=" + left + ", right=" + right + '}';
    }
}

测试方法:

public static void main(String[] args) {
    Node tree = new Node("b",
            new Node("a", null, null), new Node("c", null, null));
    System.out.println(tree);
    tree = editTree(tree, new Node("d", null, null), "c");
    System.out.println(tree);
}

结果:

Node{value=b, left=Node{value=a, left=null, right=null}, right=Node{value=c, left=null, right=null}}
Node{value=b, left=Node{value=a, left=null, right=null}, right=Node{value=d, left=null, right=null}}

最新更新