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

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!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.