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 33
44use DFS to find the maximum depth of the binary tree.
55
6+ ## A. if we use a helper function (not a good idea)
67```
78helper function explanation:
89- store the max_depth in the nonlocal variable.(outside of the helper function)
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
1723visit each node once for checking if it is a leaf node's children.
2127h for height of the tree
2228'''
2329class 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
You can’t perform that action at this time.
0 commit comments