Problem Solving/LeetCode
Today's Challenge
fabichoi
2022. 8. 12. 23:45
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
Lowest Common Ancestor of a Binary Search Tree - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
요즘 트리 문제가 많이 나옴.
순회 하면서 가장 적절한 root를 찾아서 리턴하면 되는 문제
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if (root == p or root == q or not root):
return root
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
elif left:
return left
elif right:
return right
반응형