Skip to content

Commit bf498a9

Browse files
committed
update solution: maximum-depth-of-binary-tree
1 parent beded94 commit bf498a9

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

โ€Žmaximum-depth-of-binary-tree/dusunax.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
44
use DFS to find the maximum depth of the binary tree.
55
6+
## A. if we use a helper function (not a good idea)
67
```
78
helper function explanation:
89
- store the max_depth in the nonlocal variable.(outside of the helper function)
@@ -12,6 +13,11 @@
1213
- update the max_depth when the node is a leaf node's children.
1314
```
1415
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+
1521
## TC is O(n)
1622
1723
visit each node once for checking if it is a leaf node's children.
@@ -21,7 +27,10 @@
2127
h for height of the tree
2228
'''
2329
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:
2534
max_depth = 0
2635

2736
def helper(node, count):
@@ -36,3 +45,17 @@ def helper(node, count):
3645
helper(root, max_depth)
3746

3847
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

0 commit comments

Comments
ย (0)