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);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容