Binary Tree Longest Consecutive Sequence - Teeeeeebag/LeetCode GitHub Wiki

  1. without global variable
  2. return cnt not 0 when root == null
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));
    }
}