Skip to content

Add 108. Convert Sorted Array to Binary Search Tree.md #24

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

t0hsumi
Copy link
Owner

@t0hsumi t0hsumi commented Mar 2, 2025

@SuperHotDogCat
Copy link

いいと思います。inorder順に構築する方法もあるみたいです

class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
def index_range_to_BST(left: int, right: int) -> Optional[TreeNode]:
if not left < right:

Choose a reason for hiding this comment

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

僕はnot使わず書いてましたが、not 使うこちらの方が直感に近いかもですね。
(自然言語で表現すると)区間が存在しないとなるので、こちらの方がすんなりくる気がしました。

Copy link
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます。二分探索もそうですが、これとかも、区間の取り方と成立不成立によって'='がついたりつかなかったりしてややこしいので、notを入れて統一するのが好みかもしれません

Choose a reason for hiding this comment

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

わかります。探索アルゴリズムのグリッド範囲外判定とかも not でやりたい気持ちです。

Copy link

Choose a reason for hiding this comment

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

ここらへんは趣味かと思います。私は、left >= right と左が大きいときには否定的な意味としています。

@t0hsumi
Copy link
Owner Author

t0hsumi commented Mar 2, 2025

@SuperHotDogCat コメントありがとうございます。
in-orderというと、左側再帰、真ん中のノード構築、右側再帰みたいな感じになるということですかね?
違わなければスタンプとかでリアクションいただけると嬉しいです。

Copy link

@colorbox colorbox left a comment

Choose a reason for hiding this comment

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

LGTM


middle = (left + right) // 2
left = index_range_to_BST(left, middle)
right = index_range_to_BST(middle + 1, right)
Copy link

Choose a reason for hiding this comment

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

下でコメントされていますが、int型の引数leftをTreeNodeとしても用いるのはあまり良くないと思います。

```python
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
def index_range_to_BST(left: int, right: int) -> Optional[TreeNode]:
Copy link

Choose a reason for hiding this comment

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

helperみたいな命名もありかなと思いました

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.

7 participants