File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ '''
2+ # 104. Maximum Depth of Binary Tree
3+
4+ use DFS to find the maximum depth of the binary tree.
5+
6+ ```
7+ helper function explanation:
8+ - store the max_depth in the nonlocal variable.(outside of the helper function)
9+ - base case: if the node is None, update the max_depth and return.
10+ - in the helper function, do recursive call for the left and right children of the node.
11+ - update the count for the depth of the tree.
12+ - update the max_depth when the node is a leaf node's children.
13+ ```
14+
15+ ## TC is O(n)
16+
17+ visit each node once for checking if it is a leaf node's children.
18+
19+ ## SC is O(h)
20+
21+ h for height of the tree
22+ '''
23+ class Solution :
24+ def maxDepth (self , root : Optional [TreeNode ]) -> int :
25+ max_depth = 0
26+
27+ def helper (node , count ):
28+ nonlocal max_depth
29+ if node is None :
30+ max_depth = max (max_depth , count )
31+ return
32+
33+ helper (node .left , count + 1 )
34+ helper (node .right , count + 1 )
35+
36+ helper (root , max_depth )
37+
38+ return max_depth
You can’t perform that action at this time.
0 commit comments