Tuesday, July 11, 2017

298. Binary Tree Longest Consecutive Sequence


549. Binary Tree Longest Consecutive Sequence II
88.64 % 
只考虑由上向下increasing的情况
public class Solution {
    private int max = 0;
    public int longestConsecutive(TreeNode root) {
        if (root == null) return 0;
        //TODO
        longestConsecutiveHelper(root);
        return max;
    }
    private int longestConsecutiveHelper(TreeNode root) {
        if (root == null) return 0;
        int left = longestConsecutiveHelper(root.left);
        int right = longestConsecutiveHelper(root.right);
        int length = 0;
        if (root.left != null && root.left.val == root.val + 1) {
            length = left;
        }
        if (root.right != null && root.right.val == root.val + 1) {
            length = Math.max(length, right);
        }
        length += 1;
        max = Math.max(max, length);
        return length;
    }
}



No comments:

Post a Comment