We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent a3302b3 commit c376f77Copy full SHA for c376f77
maximum-depth-of-binary-tree/ppxyn1.py
@@ -0,0 +1,38 @@
1
+# idea : DFS
2
+
3
+# time : O(n)
4
+# space : O(n)
5
6
+class Solution:
7
+ def maxDepth(self, root: Optional[TreeNode]) -> int:
8
+ # edge case
9
+ if not root:
10
+ return 0
11
+ max_depth = 0
12
+ stack = [(root, 1)]
13
+ while stack:
14
+ node, depth = stack.pop()
15
+ max_depth = max(depth, max_depth)
16
+ if node.left:
17
+ stack.append((node.left, depth+1))
18
+ if node.right:
19
+ stack.append((node.right, depth+1))
20
+ return max_depth
21
22
+# another way : Down-top : recursive
23
+# class Solution:
24
+# def maxDepth(self, root: Optional[TreeNode]) -> int:
25
+# if not root:
26
+# return 0
27
+# return 1 + max(
28
+# self.maxDepth(root.left),
29
+# self.maxDepth(root.right)
30
+# )
31
32
33
34
35
36
37
38
0 commit comments