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?

1

2 Answers 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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.