반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 236 | Lowest Common Ancestor of a Binary Tree | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
문제
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
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 q as descendants (where we allow a node to be a descendant of itself).”
조건
- The number of nodes in the tree is in the range [$2$, $10^5$].
- $-10^9$ <= Node.val <= $10^9$
- All Node.val are unique.
- p != q
- p and q will exist in the tree.
내 풀이
Tree문제는 보통 recursive로 푼다.
각각 root의 왼쪽과 오른쪽 node를 탐색했을 때, 왼쪽에 하나, 오른쪽에 하나(if r and l)가 있다면 root를 리턴한다.
만약 오른쪽에만 있다면(elif r) 오른쪽 노드를 리턴하고, 왼쪽에만 있다면(else) 왼쪽 노드를 리턴한다.
코드
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root:
if root == p or root == q:
return root
l = self.lowestCommonAncestor(root.left, p, q)
r = self.lowestCommonAncestor(root.right, p, q)
if r and l:
return root
elif r:
return r
else:
return l
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 242 | Valid Anagram | Python (0) | 2022.07.28 |
---|---|
[LeetCode] 114 | Flatten Binary Tree to Linked List | Python (0) | 2022.07.27 |
[LeetCode] 34 | Find First and Last Position of Element in Sorted Array | Python (0) | 2022.07.25 |
[LeetCode] 86 | Partition List | Python (0) | 2022.07.22 |
[LeetCode] 118 | Pascal's Trigangle | Python (0) | 2022.07.19 |
Comments