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

我的代码有问题。


此函数的目的是遍历二叉树并对其进行编辑,以便将某个点的分支替换为“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 设置为等于新编辑的树的值,然后用于重置原始树的值。不能以任何其他方式完成的原因是因为我不能在节点类中设置左右节点的值,因为这是不允许的。


www说
浏览 173回答 2
2回答

慕容3067478

在该行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;    }更新:完整的代码和测试结果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}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java