使用二进制树节点编辑功能问题

问题描述 投票:1回答:2

我遇到一些麻烦,我的代码。

该功能的目的是要遍历一个二叉树并对其进行编辑,以便从某一点分支由设下的“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;
    }

这有这样一个树(原树)首先遍历到一定值时被发现来完成。然后,里面的值的节点完全是一个新的节点,其中包含了自己的价值,自己的左边和右边的节点所取代。全局变量节点然后被设置为等于新编辑的树,然后将其用于重置原始树木值的值。它不能做任何其他方式的原因是因为我无法设置左,右节点的值在节点类,因为它是不允许的。

java binary-tree nodes treenode
2个回答
1
投票

在行current = newNode;你只是改变了current变量在方法的参考。它不会影响原来的树。您需要设置newNodevalue到前一个节点。

欲了解更多信息,请参见Is Java “pass-by-reference” or “pass-by-value”?


0
投票

分配一个新值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;
    }

UPDATE:完整代码和测试结果

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}}
© www.soinside.com 2019 - 2024. All rights reserved.