File tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +28
-0
lines changed Original file line number Diff line number Diff line change
1
+ from typing import Optional
2
+
3
+
4
+ # Definition for a binary tree node.
5
+ class TreeNode :
6
+ def __init__ (self , val = 0 , left = None , right = None ):
7
+ self .val = val
8
+ self .left = left
9
+ self .right = right
10
+
11
+
12
+ class Solution :
13
+ def maxDepth (self , root : Optional [TreeNode ]) -> int :
14
+ """
15
+ - Idea: μ΄μ§ νΈλ¦¬μ μ΅λ κΉμ΄λ νμ¬ λ
Έλμ κΉμ΄(1)μ νμ νΈλ¦¬μ μ΅λ κΉμ΄ μ€ ν° κ°μ λν κ²μΌλ‘ μ μνλ€.
16
+ - Time Complexity: O(n). nμ μ 체 λ
Έλμ μ
17
+ λͺ¨λ λ
Έλλ₯Ό νλ²μ© λ°©λ¬Ένμ¬ νμνκΈ° λλ¬Έμ O(n)μ΄ μμλλ€.
18
+ - Space Complexity: O(n). nμ μ 체 λ
Έλμ μ
19
+ μ¬κ·μ μΌλ‘ νμν λ, νΈμΆ μ€νμ μμ΄λ ν¨μ νΈμΆμ μλ μ΅λ νΈλ¦¬μ κΉμ΄μ κ°λ€.
20
+ νΈλ¦¬κ° νΈν₯λμ΄ μλ μ΅μ
μ κ²½μ°, κΉμ΄κ° nμ΄ λ μ μκΈ° λλ¬Έμ O(n)μΌλ‘ ννν μ μλ€.
21
+ """
22
+ if root is None :
23
+ return 0
24
+
25
+ left_depth = self .maxDepth (root .left )
26
+ right_depth = self .maxDepth (root .right )
27
+
28
+ return max (left_depth , right_depth ) + 1
You canβt perform that action at this time.
0 commit comments