298 longest consecutive Sequence in binary tree

Math.max(current count, Math.max(leftSubtree, rightSubtree))
current count = last count + 1 when cur val == lastVal + 1
current count = 1 when cur val != lastVal + 1

class Solution {
    public int longestConsecutive(TreeNode root) {
        if(root == null) return 0;
        int left = helper(root.left, 1, root.val);
        int right = helper(root.right, 1, root.val);
        return Math.max(left, right);
    }
    public int helper(TreeNode node, int count, int val){
        if(node == null) return count;
        if(node.val == val + 1) {
            count = count+1;
        }else{
            count = 1;
        }
        int left = helper(node.left, count, node.val);
        int right = helper(node.right, count, node.val);
        return Math.max(Math.max(left, right), count);
    }
}

你可能感兴趣的:(298 longest consecutive Sequence in binary tree)