Java recursive solution


  • 0
    C
    public int longestConsecutive(TreeNode root) {
        if(root ==null) return 0;
        return help(root, root.val, 0, 0);
    }
    
    private int help(TreeNode cur, int lookingfor, int curMax, int curSeq){
        if(cur.val == lookingfor){
            curSeq +=1;
        }else{
            curSeq = 1;
        }
        curMax = Math.max(curMax, curSeq);
        int max = curMax;
        if(cur.left!=null){
            max = Math.max(max, help(cur.left, cur.val+1, curMax, curSeq));
        }
        if(cur.right!=null){
            max = Math.max(max, help(cur.right, cur.val+1, curMax, curSeq));
        }
        return Math.max(max, curMax);
    }

Log in to reply
 

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