Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- minimum path sum
- leetcode
- LongestPalindromicSubstring
- 알고리즘
- 리트코드
- 규칙없음
- Unique Paths
- No Rules Rules
- 삼성역량테스트
- 트리
- 와썹맨
- BFS
- technical debt
- mysql #numa #swap #memory
- Envoy
- Dynamic Programmin
- list of list
- 그거봤어?
- 아마조니언
- 김태강
- 삼성인 아마조니언 되다
- 기술적 채무
- 파이썬
- 리스트의 리스트
- 프로그래머스
- 독후감
- 나는 아마존에서 미래를 다녔다
- Python
- 동적 프로그래밍
- 블린이
Archives
- Today
- Total
개발자가 되고 싶은 준개발자
[LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree 풀이 및 코드 본문
알고리즘 공부/LeetCode
[LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree 풀이 및 코드
준개발자 2021. 3. 7. 16:35문제
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and qas descendants (where we allow a node to be a descendant of itself).”
BST가 주어질 때 가장 낮은 공통의 조상을 찾아라.
코드
문제 풀면서 주의 해야 했던 사항은
- 모든 노드가 unique 하다는 것 (즉, root <= root.right이 아니라 root < root.right이라는 것!)
- 자기 자신도 자신의 조상이 될 수 있다는 것
이었다.
(만약에 해당 문제가 코딩 테스트에 나온다면 이 사항에 대해 미리 질문하여 확실히 하고 넘어가야 할 것 같다....)
공통의 조상을 찾는 것이므로 root를 먼저 방문해야 한다고 생각했다. 따라서 순회는 preorder로 진행하였다.
코드를 제출하고 나니 조금더 간추려서 쓸 수도 있을 것 같지만...우선은 이렇게 남겨두겠다...
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if q.val < p.val:
p, q = q, p
if root:
if p.val <= root.val <= q.val:
return root
if root.left:
res1 = self.lowestCommonAncestor(root.left, p, q)
if res1:
return res1
if root.right:
res2 =self.lowestCommonAncestor(root.right, p, q)
if res2:
return res2
'알고리즘 공부 > LeetCode' 카테고리의 다른 글
[LeetCode] 16. 3Sum Closest 파이썬 코드 (0) | 2021.05.29 |
---|---|
[LeetCode] 7. Reverse Integer 파이썬 코드 (0) | 2021.05.29 |
[LeetCode] 230. Kth Smallest Element in a BST 문제 및 풀이 코드 (0) | 2021.03.07 |
[LeetCode] 98. Validate Binary Search Tree 풀이 및 코드 (0) | 2021.02.27 |
[LeetCode] 100. Same Tree 풀이 및 코드 (1) | 2020.09.26 |