108. Convert Sorted Array to Binary Search Tree#29
Open
hayashi-ay wants to merge 3 commits intomainfrom
Open
Conversation
|
どのコードも読みやすかったです。 |
liquo-rice
reviewed
May 8, 2024
| return make_bst(nums, 0, len(nums)) | ||
| ``` | ||
|
|
||
| ループでも解いてみた。dequeを使っても良い。二分木はリストと違ってSentinelノードを使えない。再帰の方が楽。 |
There was a problem hiding this comment.
(読みやすいかは別にして)このようにできませんか?
sentinel = TreeNode(float('inf'), 0, len(nums) - 1)
...
return sentinel.left
Owner
Author
There was a problem hiding this comment.
あー、たしかにできますね。二分木でもsentinel nodeの値と後続の処理次第では左右どちらに欲しいノードが来るかわかりますね。
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
sentinel = TreeNode(inf)
nodes = deque([(sentinel, 0, len(nums) - 1)])
while nodes:
parent, left, right = nodes.popleft()
if left > right:
continue
middle_index = (left + right) // 2
middle_value = nums[middle_index]
node = TreeNode(middle_value)
if middle_value < parent.val:
parent.left = node
else:
parent.right = node
nodes.append((node, left, middle_index - 1))
nodes.append((node, middle_index + 1, right))
return sentinel.left
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/