Binary Tree Longest Consecutive Sequence

Given a binary tree, find the length of the longest consecutive
sequence path.

The path refers to any sequence of nodes from some starting node to
any node in the tree along the parent-child connections. The longest
consecutive path need to be from parent to child (cannot be the
reverse).

Divide and Conquer

Time Complexity
O(N)

Space Complexity
O(N)

思路

全局需要keep一个global的longest consecutive length, 还需要一个local的longest consecutive length. 注意每次return的是local的longest consecutive length. 如果符合parent.val + 1 == child.val的话,就把当前节点加上传上来的local的longest ,与global longest做比较, 如果不符合,则这里的连续就断开了,把当前点的连续长度设置为0. 加上判断条件,left != 0, right != 0, 是为了防止最后一层叶子节点的时候,出现NullPointerExceptions.

代码

public int longestConsecutive(TreeNode root) {
    // Write your code here
    if(root == null) return 0;
    int[] maxLen = new int[]{1};
    helper(root, maxLen);
    return maxLen[0];
}

private int helper(TreeNode root, int[] maxLen){
    if(root == null) return 0;
    if(root.left == null && root.right == null){
        return 1;
    }
    int left = helper(root.left, maxLen);
    int right = helper(root.right, maxLen);
    
    if(left != 0){
        if(root.val + 1 == root.left.val){
            maxLen[0] = Math.max(maxLen[0], left + 1);
        }else left = 0;
    }
    
    if(right != 0){
        if(root.val + 1 == root.right.val){
            maxLen[0] = Math.max(maxLen[0], right + 1);
        }else right = 0;
    }
    
    return Math.max(left + 1, right + 1);
}

annielulu
5 声望5 粉丝