Skip to content

235. Lowest Common Ancestor of a Binary Search Tree#77

Open
kitano-kazuki wants to merge 1 commit into
mainfrom
235-lowest-common-ancestor-of-a-binary-search-tree
Open

235. Lowest Common Ancestor of a Binary Search Tree#77
kitano-kazuki wants to merge 1 commit into
mainfrom
235-lowest-common-ancestor-of-a-binary-search-tree

Conversation

@kitano-kazuki
Copy link
Copy Markdown
Owner

Comment thread memo.md
* 左に1個存在する, 右には存在しない (このとき今のノードが`p`や`q`なはず)
* 今のノードがLCA
* BSTになっているから, ノードを辿れなくても存在がわかる!!
* O(logN)でできそう
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

平衡ではない、ずっと子が片方にしかない木もBSTの条件は満たしうるので、O(log N)は平衡な場合に限ります。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

たしかに、言及するべきでした

Comment thread memo.md

## Code1-1

* AC: 26:16
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

面接を想定すると、このアプローチに結構時間がかかっているので、アプローチを考えたときにBSTという条件を使っているか?(ただの木で考えていないか?)というメタ的な検討はあって良いかもしれません。メタ的な検討5〜10分ぐらいでCode2-2に至れていたら、そちらの方が時間コストが良いですね。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

間違いないですね。code2-2はステップ2で他の解法ないかなって思ったら割とすぐ出てきたものなので、メタ的な視点持てると良かったです。
自分自身、解法思いついた時に飛びつく癖がありそうな気はしています

Comment thread memo.md
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
node = root
while True:
left = 0
Copy link
Copy Markdown

@sasanquaneuf sasanquaneuf May 31, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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')

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

複雑になってしまっている部分を特定して固定できるとシンプルになりますね。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants