Simple Java DFS - Run time 3ms


  • 0
    public class Solution {
        public int longestConsecutive(TreeNode root) {
            if (root == null) return 0; 
            // use an array to do "object-sharing" when invoking helper function. 
            int[] maxSize = new int[1];
            helper(root, root.val, 0, maxSize);
            return maxSize[0]; 
        }
        
        private void helper(TreeNode curr, int target, int lastSize, int[] maxSize){
            int currSize = 1;
            if (curr.val == target) currSize += lastSize; 
            maxSize[0] = Math.max(currSize, maxSize[0]); 
            
            if (curr.left != null) helper(curr.left, curr.val + 1, currSize, maxSize); 
            if (curr.right != null) helper(curr.right, curr.val + 1, currSize, maxSize); 
            
            return; 
        }
    }
    

Log in to reply
 

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