My 1ms Java solution without static variable


  • 0
    S
    public class Solution {
        public int longestConsecutive(TreeNode root) {
            if (root == null) return 0;
            
            return recur(root, root.val - 1, 0);
        }
        
        private int recur(TreeNode node, int upper, int count) {
            if (node == null) return count;
            
            int val = node.val;
            
            if (upper - val == -1) {
                return Math.max(count + 1, Math.max(recur(node.left, node.val, count + 1),
                                                    recur(node.right, node.val, count + 1)));
            } else {
                return Math.max(count, Math.max(recur(node.left, node.val, 1),
                                                recur(node.right, node.val, 1)));
            }
        }
    }
    

Log in to reply
 

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