Maybe it is just as simple:
public static int longestPath(Node n) {
if (n != null) {
return longestPath(n, 0); // forgot return?
}
return 0;
}
Its more complicated than one might think at first sight. Consider the following tree:
1
/
2 3
/
4 5
/
6 7 8
/
9 a b
In this case, the root node is not even in the longest path (a-7-4-2-5-8-b
).
So, what you must do is the following: For each node n
you must compute the following:
- compute longest path in left subtree starting with the root of the left subtree (called
L
)
- compute longest path in right subtree starting with the root of the right subtree (called
R
)
- compute the longest path in left subtree (not necessarily starting with the root of the left subtree) (called
l
)
- compute the longest path in right subtree (not necessarily starting with the root of the right subtree) (called
r
)
Then, decide, which combination maximizes path length:
L+R+2
, i.e. going from a subpath in left subtree to current node and from current node through a subpath in right subtree
l
, i.e. just take the left subtree and exclude the current node (and thus right subtree) from path
r
, i.e. just take the right subtree and exclude the current node (and thus left subtree) from path
So I would do a little hack and for every node not return just a single int
, but a triple of integers containing (L+R+2, l, r)
. The caller then must decide what to do with this result according to the above rules.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…