Simplest Java Solution


  • 0
    M
        public class Solution {
            int max = 0;
    	    public int longestConsecutive(TreeNode root) {
                dfs(root);
    	    	return max;
            }
    	private int[] dfs(TreeNode root) {
    		if (root == null) return new int[]{0, 0};
    		int[] l = dfs(root.left), r = dfs(root.right);
    		if (root.left != null) {
    			if (root.left.val + 1 != root.val) l[0] = 0;
    			if (root.left.val - 1 != root.val) l[1] = 0;
    		} 
    		if (root.right != null) {
    			if (root.right.val + 1 != root.val) r[0] = 0;
    			if (root.right.val - 1 != root.val) r[1] = 0;
    		}
    		int[] larger = new int[]{Math.max(l[0], r[0]) + 1, Math.max(l[1], r[1]) + 1};
    		max = Math.max(max, l[0] + r[1] + 1);
    		max = Math.max(max, l[1] + r[0] + 1);
    		return larger;
    	}
        }
    

Log in to reply
 

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