My AC Java recursive solution


  • 0
    S
    public class Solution {
        int max=0;
        public int longestConsecutive(TreeNode root) {
            longestConsecutiveR(root);
            return max;
        }
        
        public int longestConsecutiveR(TreeNode root){
            if(root==null) return 0;
            int left = longestConsecutiveR(root.left);
            int right = longestConsecutiveR(root.right);
            int r=0;
            if(left==0&&right==0){ //leaf node case
                r=1;
            } else if(left==0){  //left child is null
                r= root.val-root.right.val==-1?right+1:1;
            } else if(right==0){ //right child is null
                r= root.val-root.left.val==-1?left+1:1;
            } else {  //pick right/left child if it is consecutive, otherwise return 1 to start over
                r= Integer.max(
                    root.val-root.right.val==-1?right+1:1,
                    root.val-root.left.val==-1?left+1:1
                    );
            }
            max=Integer.max(max,r); //remember the max value
            return r;
        }
    }
    

Log in to reply
 

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