Skip to content

Commit e5b94b3

Browse files
authored
Create 104-Maximum-Depth-of-Binary-Tree.py
1 parent 4b62701 commit e5b94b3

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# RECURSIVE DFS
2+
class Solution:
3+
def maxDepth(self, root: TreeNode) -> int:
4+
if not root:
5+
return 0
6+
7+
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
8+
9+
# ITERATIVE DFS
10+
class Solution:
11+
def maxDepth(self, root: TreeNode) -> int:
12+
stack = [[root, 1]]
13+
res = 0
14+
15+
while stack:
16+
node, depth = stack.pop()
17+
18+
if node:
19+
res = max(res, depth)
20+
stack.append([node.left, depth + 1])
21+
stack.append([node.right, depth + 1])
22+
return res
23+
24+
# BFS
25+
class Solution:
26+
def maxDepth(self, root: TreeNode) -> int:
27+
if not root:
28+
return 0
29+
30+
level = 0
31+
q = deque([root])
32+
while q:
33+
34+
for i in range(len(q)):
35+
node = q.popleft()
36+
if node.left:
37+
q.append(node.left)
38+
if node.right:
39+
q.append(node.right)
40+
level += 1
41+
return level

0 commit comments

Comments
 (0)