英文:
Depth of a Node in a Binary Tree (Java)
问题
节点的深度是指从根节点到该节点的边数,对吧?但是如何通过类似于 Java 中的 findDepth(Node node) 方法来找到它呢?
英文:
The depth of a node is the number of edges from root to that node, right? But how to find it by a method like findDepth(Node node) in java?
答案1
得分: 0
以下是翻译好的内容:
这是一个关于递归的简单练习。请递归地实现它。
findDepth(Node node)
在findDepth
函数/方法的代码中执行以下操作:
1)如果节点有父节点,则返回1 + findDepth(parent)
2)如果节点没有父节点(即为根节点),则返回0
。
英文:
It's a simple exercise on recursion. Implement it recursively.
findDepth(Node node)
In the code of the findDepth
function/method do this:
- if the node has a parent return
1 + findDepth(parent)
- if the node has no parent (i.e. is the root) return
0
答案2
得分: 0
根据这个已经在StackOverflow上的答案,你可以这样做:
int findDepth(Node node) {
if (node == null) {
return -1;
}
int lefth = findHeight(node.left);
int righth = findHeight(node.right);
if (lefth > righth) {
return lefth + 1;
} else {
return righth + 1;
}
}
英文:
So, based on this answer, already on stackOverflow, you can do this:
int findDepth(Node node) {
if (aNode == null) {
return -1;
}
int lefth = findHeight(node.left);
int righth = findHeight(node.right);
if (lefth > righth) {
return lefth + 1;
} else {
return righth + 1;
}
}
专注分享java语言的经验与见解,让所有开发者获益!
评论