我遇到一些麻烦,我的代码。
该功能的目的是要遍历一个二叉树并对其进行编辑,以便从某一点分支由设下的“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;
}
这有这样一个树(原树)首先遍历到一定值时被发现来完成。然后,里面的值的节点完全是一个新的节点,其中包含了自己的价值,自己的左边和右边的节点所取代。全局变量节点然后被设置为等于新编辑的树,然后将其用于重置原始树木值的值。它不能做任何其他方式的原因是因为我无法设置左,右节点的值在节点类,因为它是不允许的。
在行current = newNode;
你只是改变了current
变量在方法的参考。它不会影响原来的树。您需要设置newNode
为value
到前一个节点。
分配一个新值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}}