如何正确穿越二进制树以返回其高度?
我已经开始实施此代码,但是现在我被卡住了。我试图将树的高度从根部恢复到最远的叶子。我能够进入外叶,但不能进入内部叶子。如何将内叶纳入功能以返回最高高度?
static int getHeight(Node root){
int left = 0;
int right = 0;
Node head = root;
while(root.left != null) {
root = root.left;
left++;
}
while(head.right != null) {
head = head.right;
right++;
}
return Math.Max(left, right);
I have started implementing this code but now I'm stuck. I'm trying to return the height of the tree from the root to the furthest leaf. I'm able to access the outside leaves but not the inner ones. How can I incorporate the inner leaves in my function in order to return the highest height?
static int getHeight(Node root){
int left = 0;
int right = 0;
Node head = root;
while(root.left != null) {
root = root.left;
left++;
}
while(head.right != null) {
head = head.right;
right++;
}
return Math.Max(left, right);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试此递归算法:
try this recursive algorithm:
您可以尝试,例如 b 读取 f irst s earch( bfs )方法(因为您想穿越):
You can try, say, Breadth First Search (BFS), let it be non-recursive approach (since you want to traverse):