在二叉树中的节点深度(Java)

huangapple 未分类评论43阅读模式
英文:

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:

  1. if the node has a parent return 1 + findDepth(parent)
  2. 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;
    }
}

huangapple
  • 本文由 发表于 2020年4月7日 21:12:11
  • 转载请务必保留本文链接:https://java.coder-hub.com/61080820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定