java short solution.


  • 0
    Z
    public int longestConsecutive(TreeNode root) {
        if(root==null) return 0;
        maxPath = 0;
        helper(root);
        return maxPath;
    }
    
    private int maxPath;
    
    // return max <increasing, decreasing> pair from bottom to top.
    private int[] helper(TreeNode root) {
        if(root==null) return new int[]{0, 0};
        int[] left = helper(root.left);
        int[] right = helper(root.right);
        int increasing = Math.max(root.left!=null && root.val==root.left.val+1 ? left[0] : 0, 
                              root.right!=null && root.val==root.right.val+1 ? right[0] : 0);
        int decreasing = Math.max(root.left!=null && root.val==root.left.val-1 ? left[1] : 0, 
                              root.right!=null && root.val==root.right.val-1 ? right[1] : 0);
        maxPath = Math.max(maxPath, 1 + increasing + decreasing);
        return new int[]{increasing + 1, decreasing + 1};
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.