Easy Java solution, One Recursive function is enough; No need global variable


  • 0
     public int longestConsecutive(TreeNode root) {
        if(root == null) return 0;
        return longestConsecutiveFrom(root , 1, root.val-1 , 0);
     }
    
    private int longestConsecutiveFrom(TreeNode root, int max_cnt, int curr_num, int curr_cnt){
        if(root==null){
            max_cnt = Math.max(max_cnt,curr_cnt);
            return max_cnt;
        }else if(root.left==null && root.right==null){
            if(root.val==curr_num+1){curr_cnt++;}else{}
            max_cnt = Math.max(max_cnt,curr_cnt);
            return max_cnt;
        }else{
            if(root.val==curr_num+1){
                int cnt_left = longestConsecutiveFrom(root.left , max_cnt, root.val, curr_cnt+1);
                int cnt_right = longestConsecutiveFrom(root.right , max_cnt, root.val, curr_cnt+1);
                
                return cnt_left>cnt_right ? cnt_left:cnt_right;
            }else{
                curr_cnt = 1;
                int cnt_left = longestConsecutiveFrom(root.left , max_cnt, root.val, curr_cnt);
                int cnt_right = longestConsecutiveFrom(root.right , max_cnt, root.val, curr_cnt);
                
                return cnt_left>cnt_right ? cnt_left:cnt_right;
            }
        }
    }

Log in to reply
 

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