simple and clear DFS solution


  • 1
    K
    public class Solution {
        public static int longestConsecutive(TreeNode root) {
            int max=1;
            if(root==null)return 0;
            return dfs(max,root);
        }
        public static int dfs(int max, TreeNode root){
            int max1=max;
            int max2=max;
            if(root==null) return max;
            if(root.left!=null&&root.left.val==root.val+1){
                max1++;
                max1= dfs(max1,root.left);
            }
            else if(root.left!=null&&root.left.val!=root.val+1){
                
                max1= longestConsecutive(root.left);
            }
            if(root.right!=null&&root.right.val==root.val+1){
                max2++;
                max2= dfs(max2,root.right);
            }
             else if(root.right!=null&&root.right.val!=root.val+1){
                max2= longestConsecutive(root.right);
            }
            return Math.max(Math.max(max1,max2),max);
        }
    }
    

Log in to reply
 

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