亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

二叉樹節點編輯功能的問題

二叉樹節點編輯功能的問題

www說 2022-06-15 09:36:56
我的代碼有問題。此函數的目的是遍歷二叉樹并對其進行編輯,以便將某個點的分支替換為“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 設置為等于新編輯的樹的值,然后用于重置原始樹的值。不能以任何其他方式完成的原因是因為我不能在節點類中設置左右節點的值,因為這是不允許的。
查看完整描述

2 回答

?
慕容3067478

TA貢獻1773條經驗 獲得超3個贊

在該行current = newNode;中,您只是更改current方法中變量的引用。它不會影響原始樹。您需要設置newNodevalue前一個節點。



查看完整回答
反對 回復 2022-06-15
?
猛跑小豬

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}}



查看完整回答
反對 回復 2022-06-15
  • 2 回答
  • 0 關注
  • 113 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號