File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ [Problem]
3+ https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
4+
5+ Return maximum depth of binary tree
6+ 0 < the number of nodes < 10,000
7+
8+ [Brainstorming]
9+ DFS를 이용해서 구해보자.
10+ 이진 트리에서 전체 탐색을 DFS로 진행했을 떄 시간 복잡도는 O(N)으로 판단된다.
11+
12+ [Complexity]
13+ N is the number of nodes
14+ Time: O(N)
15+ Space: O(N)
16+ -> node의 개수 만큼 call stack이 쌓임
17+ """
18+
19+ from typing import Optional
20+ # Definition for a binary tree node.
21+ class TreeNode :
22+ def __init__ (self , val = 0 , left = None , right = None ):
23+ self .val = val
24+ self .left = left
25+ self .right = right
26+ class Solution :
27+ def maxDepth (self , root : Optional [TreeNode ]) -> int :
28+ answer = 0
29+
30+ def dfs (depth , node :Optional [TreeNode ])-> None :
31+ nonlocal answer
32+ if not node .left and not node .right :
33+ answer = max (answer , depth )
34+ return
35+
36+ if node .left :
37+ dfs (depth + 1 , node .left )
38+ if node .right :
39+ dfs (depth + 1 , node .right )
40+
41+ if not root :
42+ return answer
43+ dfs (1 , root )
44+ return answer
45+
46+
47+ class AnotherSolution :
48+ """
49+ ref: leetcode
50+
51+ [Complexity]
52+ Time: O(N)
53+ Space: O(N)
54+ """
55+ def maxDepth (self , root :Optional [TreeNode ])-> int :
56+ if not root :
57+ return 0
58+ return 1 + max (self .maxDepth (root .left ), self .maxDepth (root .right ))
59+
60+
You can’t perform that action at this time.
0 commit comments