Java recursive solution with a global variable


  • 0
    I
    private int longest = 1;
    public int longestConsecutive(TreeNode root) {
        this.longestTop(root);
        if (root == null) return 0;
        return longest;
    }
    public int longestTop(TreeNode root) {
        if (root == null) return 0;
        if (root.right == null && root.left == null) return 1;
        int leftTemp = this.longestTop(root.left);
        int rightTemp = this.longestTop(root.right);
        int left = (root.left == null) ? 1 : (root.left.val - 1) == root.val ? leftTemp + 1: 1;
        int right = (root.right == null) ? 1 : (root.right.val - 1) == root.val ? rightTemp + 1 : 1;
        this.longest = Math.max(this.longest, Math.max(left, right));
        return Math.max(left, right);
    }

Log in to reply
 

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