二进制树中节点的深度(Java)



节点的深度是从根到该节点的边数,对吧?但是如何通过像java中的findDepth(Node Node(这样的方法找到它呢?

这是一个关于递归的简单练习。递归地实现它。

findDepth(Node node)

findDepth函数/方法的代码中执行以下操作:
1(如果节点有父级返回1 + findDepth(parent)
2(如果该节点没有父级(即根(返回0

因此,基于这个答案,已经在stackOverflow上,您可以这样做:

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

最新更新