From 388eeb5c4aef5497d5f55efdb4a702c38f4b5d40 Mon Sep 17 00:00:00 2001 From: kitaken <83747835+Kitaken0107@users.noreply.github.com> Date: Sat, 23 Mar 2024 16:22:21 +0900 Subject: [PATCH] Create 10_Lowest Common Ancestor of a Binary Search Tree.md --- ...Common Ancestor of a Binary Search Tree.md | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 10_Lowest Common Ancestor of a Binary Search Tree.md diff --git a/10_Lowest Common Ancestor of a Binary Search Tree.md b/10_Lowest Common Ancestor of a Binary Search Tree.md new file mode 100644 index 0000000..48c655f --- /dev/null +++ b/10_Lowest Common Ancestor of a Binary Search Tree.md @@ -0,0 +1,41 @@ +235. Lowest Common Ancestor of a Binary Search Tree +https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/ + +0:BSTの知識不足と問題の論理が難しかった +方針: +操作としては、p・qのノードから上のノードにたどって、 +初めて合流したときのノードがアウトプット +ただ上のノードをどのようにたどるかがわからない + +1st +以下の解答を参考にしました +方針:rootから初めて、LCAでなければ進めて、止まったらLCAを返す(値の条件をうまく使う) +・LCAの条件は2パターン + ・LCAがp・qどちらかのパターン + ・LCAがp・qの共通の親 +・なので、LCAではない条件は以下となる + ・LCA候補が
p,q + +https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/discuss/4276179/Beats-99-or-O(-log(n))-or-(Step-by-step-explanation) + +```python +# 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': + + while root: + if root.val > p.val and root.val > q.val: + root = root.left + elif root.val < p.val and root.val < q.val: + root = root.right + else: + return root +``` + +