-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0104_maximum_depth_of_binary_tree.py
More file actions
80 lines (64 loc) · 2.26 KB
/
0104_maximum_depth_of_binary_tree.py
File metadata and controls
80 lines (64 loc) · 2.26 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#------------------------------------------------------------------------------
# Questions: 0104_maximum_depth_of_binary_tree.py
#------------------------------------------------------------------------------
'''
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root
node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
'''
#------------------------------------------------------------------------------
# Solutions
#------------------------------------------------------------------------------
from typing import *
from test_utils.BinaryTree import BinaryTree, TreeNode
# tags:
class SolutionRecur:
'''Recursion'''
def maxDepth(self, root: TreeNode) -> int:
if root is None:
return 0
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
return 1 + max(left, right)
# Time = O(N) where N is the number of nodes
# Space:
# O(N): Worst case if tree is completely imbalanced and each node only has left child.
# Storage to keep the call stack will be O(N)
# O(log N): Best case if tree is balanced, since height of the tree would be Log N
class SolutionStack:
'''Stack DFS'''
def maxDepth(self, root: TreeNode) -> int:
stack = []
stack.append((1, root))
max_depth = 0
while stack:
current_depth, node = stack.pop()
if node:
max_depth = max(max_depth, current_depth)
stack.append((current_depth+1, node.left))
stack.append((current_depth+1, node.right))
return max_depth
# Time = O(N)
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
import unittest
class TestSolution1(unittest.TestCase):
def test_simple(self):
root = [3,9,20,None,None,15,7]
root = BinaryTree(root).root
s = SolutionRecur()
self.assertEqual(s.maxDepth(root), 3)
s = SolutionStack()
self.assertEqual(s.maxDepth(root), 3)
if __name__ == "__main__":
unittest.main()