gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:47:18 26 4
gpt4 key购买 nike

我的代码遇到一些问题。

此函数的目的是遍历二叉树并对其进行编辑,以便将某个点的分支替换为“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 设置为前一个节点的

有关详细信息,请参阅 Is Java “pass-by-reference” or “pass-by-value”?

关于java - 二叉树节点编辑功能的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54624493/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com