-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumDepthInBinaryTree.py
More file actions
63 lines (54 loc) · 1.78 KB
/
MaximumDepthInBinaryTree.py
File metadata and controls
63 lines (54 loc) · 1.78 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
................. DFS Recursion......................
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
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))
...........Iterative BFS .................
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
level = 0
q = deque([root])
while q:
for i in range(len(q)):
CurrNode = q.popleft()
if CurrNode.left:
q.append(CurrNode.left)
if CurrNode.right:
q.append(CurrNode.right)
level += 1
return level
........................... Iterative DFS............
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
stack = [[root, 1]]
res = 1
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