Skip to content

Conversation

Satorien
Copy link
Owner


- 初めに思い付いたのは左右との比較を行い、どんどん下りていく方法
- ただ、直後のノードを確かめるだけでは不十分なので毎回深掘る実装をする
- 時間計算量は最大O(n^2)になってしまうので流石に修正する
Copy link

Choose a reason for hiding this comment

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

線形時間にする方法として「ペアを返す再帰にすると線形時間になる」を使う方法もあります。
再帰が (最小、最大、is_valid) の3つ組を返すようにするということです。
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.r1pr4pvhjsjx

MAX_VAL = 2**31
class Solution:
def isValidBST(self, root: Optional[TreeNode]) -> bool:
nodes_and_ranges: list[tuple[int]] = [(root, MIN_VAL, MAX_VAL)]

Choose a reason for hiding this comment

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

MIN_VAL、MAX_VALを定義せず、-sys.maxint - 1sys.maxintを使って初期化しても、意図は伝わるかと思いました。

return False
nodes_and_ranges.append((node.left, min_val, node.val))
nodes_and_ranges.append((node.right, node.val, max_val))
return True

Choose a reason for hiding this comment

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

とても読みやすかったです。
Generatorを使った実装は、inorder順がソート順になるという特徴を利用していて直感的なので、練習してみると良いと思います。

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants