2 回答
TA贡献1773条经验 获得超3个赞
在该行current = newNode;中,您只是更改current方法中变量的引用。它不会影响原始树。您需要设置newNode为value前一个节点。
TA贡献1858条经验 获得超8个赞
分配一个新值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}}
添加回答
举报
