3 line JAVA DFS recursive super easy to understand


  • 0
    H

    public class Solution {
    // Algo thinking: recursive looking for a global max DFS
    // time = O(N), space = O(logN)

    private int maxL = 0;
    public int longestConsecutive(TreeNode root) {
        if (root == null) return 0;
        recursive(root, 1);
        return maxL;
    }
    
    private void recursive (TreeNode root, int len) {
        
        maxL = Math.max(maxL, len);
        
        if (root.left != null) recursive(root.left, root.val - root.left.val == -1 ? len + 1 : 1);
        
        if (root.right != null) recursive(root.right, root.val - root.right.val == -1 ? len + 1 : 1);
    }
    

    }


Log in to reply
 

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