File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change 1+ from typing import Optional
2+
3+ # Definition for a binary tree node.
4+ class TreeNode :
5+ def __init__ (self , val = 0 , left = None , right = None ):
6+ self .val = val
7+ self .left = left
8+ self .right = right
9+
10+ class Solution :
11+ """
12+ - Time Complexity: O(n), n = The number of nodes in tree
13+ - Space Complexity: O(H), H = The height of tree,
14+ - H = logn, if the tree is balanced
15+ - H = n, if the tree is skewed
16+ """
17+ def maxDepth (self , root : Optional [TreeNode ]) -> int :
18+ if not root :
19+ return 0
20+
21+ # dfs : count the depth
22+ max_depth = 0
23+
24+ def dfs (node , count ):
25+ nonlocal max_depth
26+
27+ if not node :
28+ max_depth = max (max_depth , count )
29+ return
30+
31+ dfs (node .left , count + 1 )
32+ dfs (node .right , count + 1 )
33+
34+ dfs (root , 0 )
35+
36+ return max_depth
37+
38+ def doTest ():
39+ sol = Solution ()
40+
41+ root1 = TreeNode (3 )
42+ root1 .left = TreeNode (9 )
43+ root1 .right = TreeNode (20 )
44+ root1 .right .left = TreeNode (15 )
45+ root1 .right .right = TreeNode (7 )
46+ print ("TC 1 is Success!" if sol .maxDepth (root1 ) == 3 else "TC 1 is Failed!" )
47+
48+ root2 = TreeNode (1 )
49+ root2 .right = TreeNode (2 )
50+ print (f"TC 2 is Success!" if sol .maxDepth (root2 ) == 2 else "TC 2 is Failed!" )
51+
52+ print (f"TC 3 is Success!" if sol .maxDepth (None ) == 0 else "TC 3 is Failed!" )
53+ doTest ()
You can’t perform that action at this time.
0 commit comments