I have a tree, and I want to find the depth of it. For example for this tree:

0        root
        /    \
1      5      1
      / \
2     1   3
3     2

It should give a depth of 3.

public int getDepth() {
		int maxDepth = 0;
		if(this.hasChildren()) {
			for(int i = 0; i < children.size(); i++) {
				maxDepth = Math.max(maxDepth, children.get(i).getDepth());
			return maxDepth;
		else {
			return 1;

Could you point out what's wrong so that you can fix it? Please don't just hand me correct code; (I heard that this is against the rules, anyway) tell me what's wrong so I can figure it out myself!

Thanks in advance!:)

7 Years
Discussion Span
Last Post by Awesomeness

I don't think Math.max is what you need to solve this problem. It seems to me that at each level you just want to add 1 to maxDepth.


Oh, lol, I forgot the + 1. Stupid me. Oh well...

I'm embarrassed. Thanks!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.