Simple Java Recursive Solution


  • 1
    B

    public class Solution {

    int max;
    public int longestConsecutive(TreeNode root) {
        if(root == null){
            return 0;
        }
        
        max = 0;
        helper(root,root,0);
        return max;
        
    }
    
    public void helper(TreeNode root,TreeNode pre, int count){
        if(root == null){
            return;
        }
        if(pre.val+1 == root.val){
            count += 1;
        }else{
            count = 1;
        }
        if(count>max){
            max = count;
        }
        helper(root.left,root,count);
        helper(root.right,root,count);
    }
    

    }


Log in to reply
 

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