-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path104_maximumDepthOfBinaryTree.py
39 lines (35 loc) · 1.02 KB
/
104_maximumDepthOfBinaryTree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
## Recursive
#class Solution:
# def maxDepth(self, root: Optional[TreeNode]) -> int:
# if not root:
# return 0
#
# return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
## BFS
#class Solution:
# def maxDepth(self, root: Optional[TreeNode]) -> int:
# q = deque()
# if root:
# q.append(root)
# level = 0
# while q:
# for i in range(len(q)):
# node = q.popleft()
# if node.left:
# q.append(node.left)
# if node.right:
# q.append(node.right)
# level += 1
# return level
## DFS
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
stack = [[root, 1]]
res = 0
while stack:
node, depth = stack.pop()
if node:
res = max(res, depth)
stack.append([node.left, depth + 1])
stack.append([node.right, depth + 1])
return res