1

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?

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
  • 2
    Does this answer your question? [Finding height in Binary Search Tree](https://stackoverflow.com/questions/2597637/finding-height-in-binary-search-tree) – Arvind Kumar Avinash Apr 07 '20 at 13:15

2 Answers2

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

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
0

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;
    }
}
Raul Lucaciu
  • 132
  • 7