Easy, Neat and modular java Recursive solution.


  • 0
    P

    The key idea is take max of the length till now and the max of left and right length. Following is the simple implementation :

    public int longestConsecutive(TreeNode root) {
            if(root == null)
                return 0;
            return longestConsecutive(root, null, 0);
        }
        public int longestConsecutive(TreeNode root, TreeNode prev, int len) {
            if(root == null)
                return len; // reached the leaf node.
    
            int leftLen = 0, rightLen = 0;
            if(prev != null && root.val == prev.val + 1) { // Increasing node found
                leftLen = longestConsecutive(root.left, root, len + 1);
                rightLen = longestConsecutive(root.right, root, len + 1);
            }
            else { // This node breaks the increasing property. So start again from here.
                leftLen = Math.max(len, longestConsecutive(root.left, root, 1));
                rightLen = Math.max(len, longestConsecutive(root.right, root, 1));
            }
    
                
            return Math.max(leftLen, rightLen);
            
        }
    

Log in to reply
 

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