-
Notifications
You must be signed in to change notification settings - Fork 0
10_Lowest Common Ancestor of a Binary Search Tree.md #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 or >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: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. これ、< で統一したほうが読みやすくないですか? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 私の趣味はこんなんですね。 if p.val < root.val and q.val < root.val: 両方左にあったら左に行って、再挑戦。 |
||
| root = root.left | ||
| elif root.val < p.val and root.val < q.val: | ||
| root = root.right | ||
| else: | ||
| return root | ||
| ``` | ||
|
|
||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.