1ms easy to understand java solution, just traverse the tree once

  • 7
    public int longestConsecutive(TreeNode root) {
       int[] ret    = new int[]{0};
       int   curLen = 0;
       helper(null, root, curLen, ret);
       return ret[0];
    private void helper(TreeNode parent, TreeNode cur, int curLen, int[] ret){
        if(cur == null){
        curLen =   parent == null || cur.val != parent.val + 1
                 ? 1
                 : curLen + 1;
        ret[0] = Math.max(ret[0], curLen);
        helper(cur, cur.left,  curLen, ret);
        helper(cur, cur.right, curLen, ret);

  • 0

    Why is ret an int array. Can it be a int?

  • 0

    int does not work. We need to pass in a reference to an object so that any changes to this object will be visible

Log in to reply

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