15 lines Simple Java Recursion Solution


  • 0
    D
    public class Solution {
        
        int rt = 0;
        
        public void recur( TreeNode root, int last, int counter ) {
            
            if ( root == null ) {
                rt = Integer.max( rt, counter );
                return;
            }
            
            if ( root.val == last + 1 ) {
                counter++;
            } else {
                rt = Integer.max( rt, counter );
                counter = 1;
            }
            
            recur( root.left, root.val, counter );
            recur( root.right, root.val, counter );
        }
        
        public int longestConsecutive(TreeNode root) {
            
            if ( root == null )
                return 0;
            
            recur( root, Integer.MIN_VALUE, 1 );
            
            return rt;
        }
    }

Log in to reply
 

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