Java easy to understand recursive solution.


  • 0
    C
    public int longestConsecutive(TreeNode root) {
        // ret[0] is the max length when includes node "root", 
        // ret[1] is the max length when doesn't include node "root"
        int[] ret = helper(root); 
        return Math.max(ret[0], ret[1]);
    }
    
    private int[] helper(TreeNode root) {
        int[] ret = new int[2];
        if (root == null) {
            return ret;
        }
        int[] a = helper(root.left);
        int[] b = helper(root.right);
        int m = 1;
        if (root.left != null && root.left.val == root.val+1) {
            m = a[0] +1;
        }
        if (root.right != null && root.right.val == root.val+1) {
            m = Math.max(m, b[0]+1);
        }
        ret[0] = m;
        ret[1] = Math.max(Math.max(a[0], a[1]), Math.max(b[0], b[1]));
        return ret;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.