给一棵二叉树,找到最长连续路径的长度。
这条路径是指 任何的节点序列中的起始节点到树中的任一节点都必须遵循 父-子 联系。最长的连续路径必须是从父亲节点到孩子节点(不能逆序)。
样例
举个例子:
1
3
/
2 4
5
最长的连续路径为 3-4-5,所以返回 3。
2
3
/
2
/
1
最长的连续路径为 2-3 ,而不是 3-2-1 ,所以返回 2。
public int longestConsecutive(TreeNode root) {
// write your code here
return helper(root,null,0);
}
public int helper(TreeNode root,TreeNode parent,int length){
if(root == null) return 0;
length = (parent != null && parent.val == root.val - 1) ? length + 1 : 1;
int left = helper(root.left,root,length);
int right = helper(root.right,root,length);
return Math.max(length,Math.max(left,right));
}