File tree Expand file tree Collapse file tree 2 files changed +76
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 2 files changed +76
-0
lines changed Original file line number Diff line number Diff line change
1
+ from collections import deque
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
+ class Solution :
10
+ def maxDepth (self , root : Optional [TreeNode ]) -> int :
11
+ if not root :
12
+ return 0
13
+
14
+ def bfs (n ):
15
+ queue = deque ([n ])
16
+ depth = 0
17
+
18
+ while queue :
19
+ depth += 1
20
+ for _ in range (len (queue )):
21
+ node = queue .popleft ()
22
+ if node .left :
23
+ queue .append (node .left )
24
+ if node .right :
25
+ queue .append (node .right )
26
+ return depth
27
+
28
+ def dfs (n ):
29
+ stack = [n ]
30
+ max_depth = 0
31
+ visited = {n : 1 }
32
+
33
+ while stack :
34
+ node = stack .pop ()
35
+ depth = visited [node ]
36
+ max_depth = max (max_depth , depth )
37
+ if node .left :
38
+ visited [node .left ] = depth + 1
39
+ stack .append (node .left )
40
+ if node .right :
41
+ visited [node .right ] = depth + 1
42
+ stack .append (node .right )
43
+ return max_depth
44
+
45
+ return dfs (root )
46
+
47
+
48
+ """
49
+ bfs 방식으로 left나 right가 있으면 스택에 넣고 depth + 1, dfs보다 비효율인 듯
50
+ """
Original file line number Diff line number Diff line change
1
+ # Definition for singly-linked list.
2
+ # class ListNode:
3
+ # def __init__(self, val=0, next=None):
4
+ # self.val = val
5
+ # self.next = next
6
+ class Solution :
7
+ # 시간복잡도: O(n + m) -> 두 리스트의 모든 노드를 한 번씩 방문
8
+ # 공간복잡도: O(1) -> 기존 노드 재배치, 추가 메모리 거의 없음
9
+ def mergeTwoLists (self , list1 : Optional [ListNode ], list2 : Optional [ListNode ]) -> Optional [ListNode ]:
10
+ merged_list = ListNode ()
11
+ tail = merged_list
12
+
13
+ while list1 and list2 :
14
+ if list1 .val < list2 .val :
15
+ tail .next = list1
16
+ list1 = list1 .next
17
+ else :
18
+ tail .next = list2
19
+ list2 = list2 .next
20
+ tail = tail .next
21
+
22
+ if list1 :
23
+ tail .next = list1
24
+ else :
25
+ tail .next = list2
26
+ return merged_list .next
You can’t perform that action at this time.
0 commit comments