File tree Expand file tree Collapse file tree 4 files changed +145
-0
lines changed
construct-binary-tree-from-preorder-and-inorder-traversal
longest-palindromic-substring Expand file tree Collapse file tree 4 files changed +145
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
3+ 두 개의 정수 배열 preorder와 inoder가 주어졌을 때 이진 트리를 구성하고 반환하시오.
4+ preorder = 전위 순회 : 루트 -> 왼쪽 서브트리 -> 오른쪽 서브트리
5+ inorder = 중위 순회 : 왼쪽 서브트리 -> 루트 -> 오른쪽 서브트리
6+
7+ TC: O(n), n: 노드 수
8+ SC: O(n)
9+ """
10+
11+ from typing import Optional , List
12+
13+ # Definition for a binary tree node.
14+ class TreeNode :
15+ def __init__ (self , val = 0 , left = None , right = None ):
16+ self .val = val
17+ self .left = left
18+ self .right = right
19+
20+ class Solution :
21+ def buildTree (self , preorder : List [int ], inorder : List [int ]) -> Optional [TreeNode ]:
22+ if not preorder or not inorder :
23+ return None
24+
25+ # 1. preorder의 첫 값이 root
26+ root_val = preorder [0 ]
27+ root = TreeNode (root_val )
28+
29+ # 2. inorder에서 root 위치 찾기
30+ root_index = inorder .index (root_val )
31+
32+ # 3. 왼쪽, 오른쪽 나눠서 재귀적으로 연결
33+ root .left = self .buildTree (preorder [1 :root_index + 1 ], inorder [:root_index ])
34+ root .right = self .buildTree (preorder [root_index + 1 :], inorder [root_index + 1 :])
35+
36+ return root
Original file line number Diff line number Diff line change 1+ """
2+ https://leetcode.com/problems/longest-palindromic-substring/
3+
4+ 문자열 s가 주어졌을 때, 가장 긴 팰린드롬 부분 문자열을 찾아서 반환하는 함수를 작성해라.
5+
6+ 문제 풀이
7+
8+ 1. 문자열 `s`의 모든 인덱스 `i`를 기준으로,
9+ 2. 두 종류의 중심에서 팰린드롬을 확장해 본다:
10+ - 홀수 길이: `s[i]`를 중심으로 좌우 확장 (`i, i`)
11+ - 짝수 길이: `s[i]`와 `s[i+1]`을 중심으로 좌우 확장 (`i, i+1`)
12+ 3. 각 중심에서 while문으로 `s[left] == s[right]`인 동안 확장
13+ 4. 가장 긴 팰린드롬 문자열을 계속 업데이트
14+ 5. 최종적으로 가장 긴 팰린드롬을 반환한다
15+
16+ TC: O(n^2)
17+ SC: O(1)
18+ """
19+
20+
21+ class Solution :
22+ def longestPalindrome (self , s : str ) -> str :
23+ def expand (left : int , right : int ) -> str :
24+ while left >= 0 and right < len (s ) and s [left ] == s [right ]:
25+ left -= 1
26+ right += 1
27+
28+ return s [left + 1 : right ]
29+
30+ res = ""
31+ for i in range (len (s )):
32+ temp1 = expand (i , i ) # 홀수 길이 팰린드롬
33+ temp2 = expand (i , i + 1 ) # 짝수 길이 팰린드롬
34+ if len (temp1 ) > len (res ):
35+ res = temp1
36+ if len (temp2 ) > len (res ):
37+ res = temp2
38+ return res
Original file line number Diff line number Diff line change 1+ """
2+ https://leetcode.com/problems/rotate-image/description/
3+
4+ TC: O(n^2)
5+ SC: O(1)
6+ """
7+
8+ from typing import List
9+
10+ class Solution :
11+ def rotate (self , matrix : List [List [int ]]) -> None :
12+ """
13+ Do not return anything, modify matrix in-place instead.
14+ """
15+ top , bottom = 0 , len (matrix ) - 1
16+
17+ while top < bottom :
18+ left , right = top , bottom
19+
20+ for i in range (bottom - top ):
21+ topLeft = matrix [top ][left + i ]
22+ matrix [top ][left + i ] = matrix [bottom - i ][left ]
23+ matrix [bottom - i ][left ] = matrix [bottom ][right - i ]
24+ matrix [bottom ][right - i ] = matrix [top + i ][right ]
25+ matrix [top + i ][right ] = topLeft
26+
27+ top , bottom = top + 1 , bottom - 1
28+
Original file line number Diff line number Diff line change 1+ """
2+ https://leetcode.com/problems/subtree-of-another-tree/description/
3+
4+ 두 개의 이진 트리 root와 subRoot의 루트(최상위 노드)가 주어졌을 때,
5+ root의 하위 트리 중 subRoot와 동일한 구조와 값이 있는 경우 참을 반환하고 그렇지 않은 경우 거짓을 반환
6+
7+ TC: O(n * m), n: root의 노드 수, m: subRoot의 노드 수
8+ SC: O(n + m)
9+ """
10+
11+ from typing import Optional
12+
13+ # Definition for a binary tree node.
14+ class TreeNode :
15+ def __init__ (self , val = 0 , left = None , right = None ):
16+ self .val = val
17+ self .left = left
18+ self .right = right
19+
20+ class Solution :
21+ def isSubtree (self , root : Optional [TreeNode ], subRoot : Optional [TreeNode ]) -> bool :
22+ if not root :
23+ return False
24+ if not subRoot :
25+ return True
26+
27+ def isSameTree (p , q ):
28+ # 둘 중 하나라도 None 이면,
29+ if not p or not q :
30+ # 둘 다 None 일 때만 True
31+ return not p and not q
32+ # 같이 다르면 False
33+ if p .val != q .val :
34+ return False
35+ # 왼쪽과 오른쪽 서브트리를 재귀적으로 비교
36+ return isSameTree (p .left , q .left ) and isSameTree (p .right , q .right )
37+
38+ # root에서 시작해 subRoot와 동일한 구조의 트리인지 확인
39+ if isSameTree (root , subRoot ):
40+ return True
41+
42+ # 왼쪽 또는 오른쪽 서브트리 중 하나라도 subRoot와 같은 트리가 있는지 재귀 탐색
43+ return self .isSubtree (root .left , subRoot ) or self .isSubtree (root .right , subRoot )
You can’t perform that action at this time.
0 commit comments