Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions validate-binary-search-tree.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
1回目。Gemini に聞いた

```py
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
def validate(node: Optional[TreeNode], lower_bound: float, upper_bound: float) -> bool:
if node is None:
return True
if not (lower_bound < node.val < upper_bound):
return False

is_left_valid = validate(node.left, lower_bound, node.val)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

return validate(node.left, lower_bound, node.val) and validate(node.right, node.val, upper_bound) とすると、短絡評価で速くなる場合があると思います。

is_right_valid = validate(node.right, node.val, upper_bound)
return is_left_valid and is_right_valid
return validate(root, float("-inf"), float("inf"))
```

2回目。ほかの人のコードを見る。
- これはとても勉強になる:https://github.com/quinn-sasha/leetcode/pull/27/files#r2200377284
- in-order に探索する方法を知った:https://discord.com/channels/1084280443945353267/1192736784354918470/1234120299008491581
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をin-order traversalすると昇順に並んだ数列が得られることを利用する問題はたまに見かけるような気がしますね。具体的にどこで出会ったかは思い出せませんが...

- 以下は Gemini による回答
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

これを見て何を思ったかや、再現できるように書き直したコードを書いていただけるとコメントしやすいと思います。
L27 にリストとありますが正しいでしょうか?
self.prev_val というようなインスタンス変数を使わない方法として、単に prev_val = float('-inf') として関数内関数で nonlocal prev_val と書くこともできますね。こうすることで isValidBST がスレッドセーフになると思います。

```py
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
# 直前に訪れたノードの値を保持する。
# 初期値はマイナス無限大にしておく。
# リストを使っているのは、再帰呼び出し間で値を共有・変更可能にするため。
self.prev_val = float('-inf')

def inorder_traversal(node):
if not node:
return True

# 1. 左の部分木を探索
if not inorder_traversal(node.left):
return False

# 2. 現在のノードを処理
# 現在のノードの値が直前の値以下なら、BSTではない
if node.val <= self.prev_val:
return False
# 直前の値を現在のノードの値で更新
self.prev_val = node.val

# 3. 右の部分木を探索
if not inorder_traversal(node.right):
return False

return True

return inorder_traversal(root)
```
- 他人のコードを読むのつらいなあ...

3回目。1回目のまま終了。