-
Notifications
You must be signed in to change notification settings - Fork 0
108. Convert Sorted Array to Binary Search Tree #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
MA-yo-TA
wants to merge
1
commit into
main
Choose a base branch
from
108-Convert-Sorted-Array-to-Binary-Search-Tree
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| # 108. Convert Sorted Array to Binary Search Tree | ||
|
|
||
| https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/ | ||
|
|
||
| ## step1(まず通す) | ||
|
|
||
| 元の配列がソートされているので、二分探索する要領で左右配列の分かれ目(中間)を繋いでいけばいい | ||
| 再帰で書くのがわかりやすい。 | ||
|
|
||
| ## step2(整形&他の人のコードを読む) | ||
|
|
||
| ループでも書く。部分配列を毎回スタックに詰めるのは効率が悪いので、区間の先頭と末尾のインデックスだけ持つようにする。step1.py は毎回配列をスライスしているのでちょっと遅い。スライスする長さは木の階層ごとに半分ずつになっていくのでn := len(nums) としたとき時間計算量は O(n log n)。 | ||
|
|
||
| - https://github.com/naoto-iwase/leetcode/pulls | ||
| - 「(再帰の base case は)1も含めると直感で倍速くなる。(二分木の構造または本問の再帰構造より)」 | ||
| - 確かにそうだ。葉の左右の子(None)に対する関数呼び出しがなくなるので。 | ||
| - https://github.com/shintaro1993/arai60/pull/28/changes#diff-5db3d349f04f651e2faacefca7e2937a523f2fd8c8b6cbd30ad1e7ed699f8d3aR36 | ||
| - 添え字の再帰 | ||
|
|
||
| ```python | ||
| class Solution: | ||
| def sortedArrayToBST(self, nums: list[int]) -> Optional[TreeNode]: | ||
| def interval_to_BST(head, tail) -> Optional[TreeNode]: | ||
| if head == tail: | ||
| return None | ||
|
|
||
| center = (tail + head) // 2 | ||
| return TreeNode( | ||
| val=nums[center], | ||
| left=interval_to_BST(head, center), | ||
| right=interval_to_BST(center + 1, tail), | ||
| ) | ||
|
|
||
| return interval_to_BST(0, len(nums)) | ||
| ``` | ||
|
|
||
| - https://github.com/shintaro1993/arai60/pull/28/changes#diff-5db3d349f04f651e2faacefca7e2937a523f2fd8c8b6cbd30ad1e7ed699f8d3aR91 | ||
| - 添え字の範囲について。「自分は、0 と len(nums) で始めるのが好きだと思った。」私も同じ好み。 | ||
|
|
||
| ## step3(10分以内にさっとかける \* 3回) | ||
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| from typing import Optional | ||
|
|
||
|
|
||
| class TreeNode: | ||
| def __init__(self, val=0, left=None, right=None): | ||
| self.val = val | ||
| self.left = left | ||
| self.right = right | ||
|
|
||
|
|
||
| class Solution: | ||
| def sortedArrayToBST(self, nums: list[int]) -> Optional[TreeNode]: | ||
| if not nums: | ||
| return None | ||
|
|
||
| center = len(nums) // 2 | ||
| return TreeNode( | ||
| val=nums[center], | ||
| left=self.sortedArrayToBST(nums[:center]), | ||
| right=self.sortedArrayToBST(nums[center + 1 :]), | ||
| ) |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| from typing import Optional | ||
|
|
||
|
|
||
| class TreeNode: | ||
| def __init__(self, val=0, left=None, right=None): | ||
| self.val = val | ||
| self.left = left | ||
| self.right = right | ||
|
|
||
|
|
||
| class Solution: | ||
| def sortedArrayToBST(self, nums: list[int]) -> Optional[TreeNode]: | ||
| if not nums: | ||
| return None | ||
|
|
||
| root = TreeNode() | ||
| stack: list[tuple[int, int, TreeNode]] = [(0, len(nums), root)] | ||
| while stack: | ||
| head, tail, node = stack.pop() | ||
| center = (tail + head) // 2 | ||
| node.val = nums[center] | ||
| if head < center: | ||
| node.left = TreeNode() | ||
| stack.append((head, center, node.left)) | ||
| if center + 1 < tail: | ||
| node.right = TreeNode() | ||
| stack.append((center + 1, tail, node.right)) | ||
|
|
||
| return root |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| class TreeNode: | ||
| def __init__(self, val=0, left=None, right=None): | ||
| self.val = val | ||
| self.left = left | ||
| self.right = right | ||
|
|
||
|
|
||
| class Solution: | ||
| def sortedArrayToBST(self, nums: list[int]) -> Optional[TreeNode]: | ||
| if not nums: | ||
| return None | ||
|
|
||
| root = TreeNode() | ||
| stack: list[tuple[int, int, TreeNode]] = [(0, len(nums), root)] | ||
| while stack: | ||
| head, tail, node = stack.pop() | ||
| center = (head + tail) // 2 | ||
| node.val = nums[center] | ||
| if head < center: | ||
| node.left = TreeNode() | ||
| stack.append((head, center, node.left)) | ||
| if center + 1 < tail: | ||
| node.right = TreeNode() | ||
| stack.append((center + 1, tail, node.right)) | ||
|
|
||
| return root |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
head と tail は、リンクトリストの先頭と末尾のノードを表す単語だと思います。先頭のインデックスと末尾の次のインデックスを表す場合には、あまり使わないように思います。 begin/end はいかがでしょうか?
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ありがとうございます。
そうでしたか。
確かに他の方のコードでは left/right や start/end, begin/end がよく出てきていました。
begin/end を使うようにします。