11 lines Java Solution without global variables


  • 0
    M
            public int longestConsecutive(TreeNode root) {
    		if (root == null) return 0;
                    return Math.max(longest(root.left, root.val, 1), longest(root.right, root.val, 1));
            }
    	private int longest(TreeNode root, int pVal, int pLen) {
    		if (root == null) return pLen;
    		if (root.val == pVal + 1) {
    			return Math.max(longest(root.left, root.val, pLen + 1), longest(root.right, root.val, pLen + 1));
    		}
    		int left = longest(root.left, root.val, 1), right = longest(root.right, root.val, 1);
    		return Math.max(pLen, Math.max(left, right));
    	}
    

Log in to reply
 

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