LintCode614 二叉树最长连续序列II

给定一棵二叉树,找到最长连续序列路径的长度。
路径起点跟终点可以为二叉树的任意节点。

样例
1
/
2 0
/
3
返回 4 // 0-1-2-3

class Solution {
    private int maxLen = 0;
    public int longestConsecutive(TreeNode root) {
        //use recursion for tree 
        //should maintain two variables: increasing/decreasing sequence lengths
        helper(root);
        return maxLen;
    }
    private int[] helper(TreeNode root) {
        //terminate condition
        if (root == null) return new int[]{0, 0};
        
        //do recursion
        int[] left = helper(root.left);
        int[] right = helper(root.right);
        
        //update increasing/decreasing sequence lengths: inc/dec
        int inc = 1, dec = 1;
        if (root.left != null) {
            if (root.left.val == root.val-1) inc = left[0]+1;
            if (root.left.val == root.val+1) dec = left[1]+1;
        }
        if (root.right != null) {
            if (root.right.val == root.val-1) inc = Math.max(inc, right[0]+1);
            if (root.right.val == root.val+1) dec = Math.max(dec, right[1]+1);
        }
        
        //update max length: maxLen
        maxLen = Math.max(maxLen, inc+dec-1);
        
        //pass in inc/dec into higher level recursion
        return new int[]{inc, dec};
    }
}

猜你喜欢

转载自blog.csdn.net/fruit513/article/details/85553807