954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Recursive function through tree

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!:)

Awesomeness
Newbie Poster
16 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
 

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.

kramerd
Posting Pro in Training
403 posts since Sep 2010
Reputation Points: 49
Solved Threads: 73
 

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

I'm embarrassed. Thanks!

Awesomeness
Newbie Poster
16 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: