235. Lowest Common Ancestor of a Binary Search Tree#77
Open
kitano-kazuki wants to merge 1 commit into
Open
Conversation
| * 左に1個存在する, 右には存在しない (このとき今のノードが`p`や`q`なはず) | ||
| * 今のノードがLCA | ||
| * BSTになっているから, ノードを辿れなくても存在がわかる!! | ||
| * O(logN)でできそう |
There was a problem hiding this comment.
平衡ではない、ずっと子が片方にしかない木もBSTの条件は満たしうるので、O(log N)は平衡な場合に限ります。
|
|
||
| ## Code1-1 | ||
|
|
||
| * AC: 26:16 |
There was a problem hiding this comment.
面接を想定すると、このアプローチに結構時間がかかっているので、アプローチを考えたときにBSTという条件を使っているか?(ただの木で考えていないか?)というメタ的な検討はあって良いかもしれません。メタ的な検討5〜10分ぐらいでCode2-2に至れていたら、そちらの方が時間コストが良いですね。
Owner
Author
There was a problem hiding this comment.
間違いないですね。code2-2はステップ2で他の解法ないかなって思ったら割とすぐ出てきたものなので、メタ的な視点持てると良かったです。
自分自身、解法思いついた時に飛びつく癖がありそうな気はしています
| def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': | ||
| node = root | ||
| while True: | ||
| left = 0 |
There was a problem hiding this comment.
left, rightを使わないといけないのはpとqの左右が一定しないからだと思うので、p.val > q.valのときに入れ替えると、単純な比較で書けると思います。
これを単純な比較にして、あと実装の幅として再帰にしてみると以下のようにも書けます。
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p.val > q.val:
return self.lowestCommonAncestor(root, q, p)
if p.val <= root.val <= q.val:
return root
if q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
if root.val < p.val:
return self.lowestCommonAncestor(root.right, p, q)
raise Exception('something went wrong')
Owner
Author
There was a problem hiding this comment.
複雑になってしまっている部分を特定して固定できるとシンプルになりますね。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/