Easy Java solution using dfs


  • 0
    T
    class Solution {
        
        private int maxLen = 1;
        
        public int longestConsecutive(TreeNode root) {
            dfs(root,Integer.MIN_VALUE,1);
            return root==null ? 0: maxLen;
        }
        
        //dfs to check if each child's value = parent's value + 1. 
        //if yes, increment len, and update maxLen accordingly.
        //if not, reset len=1 and continue dfs;
        
        public void dfs(TreeNode node, int parent, int len){
            if(node==null) return;
            
            if(node.val==parent+1) len++;
            else len=1;
            
            if(len>maxLen) maxLen = len;
            
            dfs(node.left, node.val, len);
            dfs(node.right, node.val, len);
        }
    }
    

Log in to reply
 

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