gpt4 book ai didi

java - 转换原始二叉树以将其装饰为预序索引

转载 作者:行者123 更新时间:2023-11-29 05:47:03 24 4
gpt4 key购买 nike

我试过了,它对左子树有效,但对右子树无效。

我很接近,但我的逻辑是错误的,任何人都可以帮助纠正和解释这个逻辑。

public static MyNode preOrderNumbering(MyNode n) {
if (n != null) {
n.obj = 0; // Set root decoration to 0;
preOrderHelper(n, 1); // Set decorations according to preorder.
}
return n;
}

public static MyNode preOrderHelper(MyNode n, int counter) {
if (n != null) {
if (n.left != null) {
n.left.obj = counter++; // Set the left object decoration to current count + 1;
preOrderHelper(n.left, counter);
}
if (n.right != null) {
n.right.obj = counter++; // Set the left object decoration to current count + 1;
preOrderHelper(n.right, counter);
}
}
return n;
}

之前:http://puu.sh/2k2H7.png

之后: enter image description here

最佳答案

在转到右侧之前,您需要使用在左侧 上发现的所有内容更新计数器

像这样:

public static int preOrderNumbering(MyNode n, int count){
if(n != null){
n.obj = ++count;

count = preOrderNumbering(n.left, count);
count = preOrderNumbering(n.right, count);

}
return count;
}

关于java - 转换原始二叉树以将其装饰为预序索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15486523/

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