Skip to content

Latest commit

 

History

History
35 lines (26 loc) · 630 Bytes

Maximum Depth of Binary Tree.md

File metadata and controls

35 lines (26 loc) · 630 Bytes

Notes

This problem defines a 1-TreeNode tree to have height of 1.

Provided code

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
}

Solution

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

Time/Space Complexity

  • Time Complexity: O(n) since we must touch all nodes
  • Space Complexity: O(n) due to recursion (on a tree that may not be balanced)

Links