Skip to content

Commit 111ad0b

Browse files
committed
O(n) time and O(n) space for implicit stack using recursion
1 parent 0b93a71 commit 111ad0b

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
Given a binary tree, find its maximum depth.
3+
4+
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
5+
6+
Note: A leaf is a node with no children.
7+
8+
Example:
9+
10+
Given binary tree [3,9,20,null,null,15,7],
11+
12+
3
13+
/ \
14+
9 20
15+
/ \
16+
15 7
17+
return its depth = 3.
18+
"""
19+
# Definition for a binary tree node.
20+
# class TreeNode:
21+
# def __init__(self, x):
22+
# self.val = x
23+
# self.left = None
24+
# self.right = None
25+
26+
class Solution:
27+
def maxDepth(self, root: TreeNode) -> int:
28+
d = 0
29+
def depth(node):
30+
nonlocal d
31+
if not node:
32+
return 0
33+
left = depth(node.left)
34+
right = depth(node.right)
35+
d = max(d,left+right)
36+
return max(left,right)+1
37+
return depth(root)

0 commit comments

Comments
 (0)