Recursive Java DFS solution


  • 0
    M
        int maxPath = Integer.MIN_VALUE;
        
        public int longestConsecutive(TreeNode root) {
            if (root == null) {
                return 0;
            }
            
            longestConsecutiveUtil(root, 1);
            
            return maxPath;
        }
        
        public void longestConsecutiveUtil(TreeNode root, int len) {
            
            if (root == null) {
                return;
            }
            
            if (root.left != null && root.val == root.left.val - 1) {
                longestConsecutiveUtil(root.left, len + 1);                
            } else {
                longestConsecutiveUtil(root.left, 1);
            }
            
            if (root.right != null && root.val == root.right.val - 1) {
                longestConsecutiveUtil(root.right, len + 1);                
            } else {
                longestConsecutiveUtil(root.right, 1);
            } 
            
            maxPath = Math.max(maxPath, len);        
        }
    

Log in to reply
 

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