My simple Java AC code


  • 0
    Y
    public class Solution {
        private int total = 0;
        public int longestConsecutive(TreeNode root) {
            helper(root);
            return total;
        }
        public int helper(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int max = 1;
            int left = helper(root.left);
            int right = helper(root.right);
            if (root.left != null && root.val == root.left.val - 1) {
                max = Math.max(left + 1, max);
            }
            if (root.right != null && root.val == root.right.val - 1) {
                max = Math.max(right + 1, max);
            }
            total = Math.max(max, total);
            return max;
        }
    }
    

Log in to reply
 

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