Java recursive solution


  • 5

    Recursively call search(TreeNode root, int length, TreeNode parent) to get result.

    public int longestConsecutive(TreeNode root) {
        return search(root, 0, null);
    }
    
    private int search(TreeNode root, int length, TreeNode parent) {
        if (root == null) { return length; }
        if (parent == null || parent.val + 1 != root.val) {
            length = 0;
        }
        length += 1;
        int left = search(root.left, length, root);
        int right = search(root.right, length, root);
        return Math.max(length, Math.max(left, right));
    }

Log in to reply
 

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