gpt4 book ai didi

c - BST 后序遍历中的打印深度

转载 作者:太空宇宙 更新时间:2023-11-04 01:45:05 25 4
gpt4 key购买 nike

所以现在我实现了顺序遍历,我需要打印节点所在位置的深度。所以如果我的树是这样的:

                                  5
/ \
2 9
\ /
3 7

然后当它打印 3 时它的深度应该是 2。如果我递归调用它,我应该在哪里增加深度。如果我沿着树向上移动,我将如何减少它?

我的代码是

void post_order(BST* root,int level)
if(root == NULL){
return;
}
post_order(root -> left,level);
post_order(root -> right, level);
//Here I would print the node info and depth
}

我要问的是我应该在哪里增加级别以显示节点的适当深度以及为什么?

最佳答案

无需增加/减少级别。当您进行递归调用时,只需传入一个比当前级别大 1 的值,当堆栈展开时,前一级别的级别仍将是递归调用之前的值。

当然,您打印关卡的位置将决定您在遍历树时看到的打印关卡的顺序。

void post_order(BST* root,int level)
if(root == NULL){
return;
}
post_order(root -> left,level + 1);
post_order(root -> right, level + 1);
//Here I would print the node info and depth
}

关于c - BST 后序遍历中的打印深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55203127/

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