Java O(n) Easy To Understand Solution


  • 0
    B

    Explanation
    The idea to this question is to recursively visit each node in our tree rooted at root through DFS.

    Time Complexity
    The time complexity is O(n) where n is the number of nodes of the tree rooted at input root, since we visit each node once through our recursive calls.

    class Solution {
        public int maxDepth(TreeNode root) {
            if (root == null) {
                return 0;
            } else {
                return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
            }
        }
    }
    

Log in to reply
 

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