File tree Expand file tree Collapse file tree 1 file changed +24
-1
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +24
-1
lines changed Original file line number Diff line number Diff line change 3
3
4
4
use DFS to find the maximum depth of the binary tree.
5
5
6
+ ## A. if we use a helper function (not a good idea)
6
7
```
7
8
helper function explanation:
8
9
- store the max_depth in the nonlocal variable.(outside of the helper function)
12
13
- update the max_depth when the node is a leaf node's children.
13
14
```
14
15
16
+ ## B. return the max_depth directly
17
+ ๐ why helper function is not necessary?
18
+ recursion function can return the max_depth directly.
19
+ remove side effect & non-local variable.
20
+
15
21
## TC is O(n)
16
22
17
23
visit each node once for checking if it is a leaf node's children.
21
27
h for height of the tree
22
28
'''
23
29
class Solution :
24
- def maxDepth (self , root : Optional [TreeNode ]) -> int :
30
+ '''
31
+ A. first approach with side effect
32
+ '''
33
+ def maxDepthWithHelper (self , root : Optional [TreeNode ]) -> int :
25
34
max_depth = 0
26
35
27
36
def helper (node , count ):
@@ -36,3 +45,17 @@ def helper(node, count):
36
45
helper (root , max_depth )
37
46
38
47
return max_depth
48
+
49
+ '''
50
+ B. return the max_depth directly.
51
+ - more concise & readable
52
+ - no side effect & non-local variable
53
+ '''
54
+ def maxDepth (self , root : Optional [TreeNode ]) -> int :
55
+ if root is None :
56
+ return 0
57
+
58
+ left_count = self .maxDepth (root .left )
59
+ right_count = self .maxDepth (root .right )
60
+
61
+ return max (left_count , right_count ) + 1
You canโt perform that action at this time.
0 commit comments