-
Notifications
You must be signed in to change notification settings - Fork 0
Binary Tree Longest Consecutive Sequence
Tim_Gao edited this page Sep 16, 2016
·
2 revisions
- without global variable
- return cnt not 0 when root == null
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int dfs(TreeNode n, int cnt, int parentVal){
if(n == null){
//don't return 0 here, when there is only one node in the tree
return cnt;
}
cnt = (parentVal+1 == n.val) ? cnt+1 : 1;
int left = dfs(n.left, cnt, n.val);
int right = dfs(n.right, cnt, n.val);
return Math.max(Math.max(left, right), cnt);
}
public int longestConsecutive(TreeNode root) {
return (root == null )?0 : Math.max(dfs(root.left, 1, root.val), dfs(root.right, 1, root.val));
}
}