-
Notifications
You must be signed in to change notification settings - Fork 0
【Arai60】24問目 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
Conversation
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.
すごく気になるところはなかったです。
root = TreeNode(nums[mid]) | ||
queue = deque([(root, (0, mid - 1), (mid + 1, len(nums) - 1))]) | ||
while queue: | ||
node, left_range, right_range = queue.popleft() |
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.
parentとかでもいいかも。
node, left_range, right_range = queue.popleft() | |
parent, left_range, right_range = queue.popleft() |
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.
BFSの方はparentの方が分かりやすいですね。
queue = deque([(root, (0, mid - 1), (mid + 1, len(nums) - 1))]) | ||
while queue: | ||
node, left_range, right_range = queue.popleft() | ||
if left_range[0] <= left_range[1]: |
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.
関数に切り出すとかしても良いかも。うまく切り出せるかは試してないですが。
node.right = helper(mid + 1, right) | ||
return node | ||
|
||
return helper(0, len(nums) - 1) |
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.
helperでも良いんですが具体的な命名をしても良いかもですね。
class Solution: | ||
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: | ||
mid = (len(nums) - 1) // 2 | ||
root = TreeNode(nums[mid]) |
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.
LeetCodeの制約ではlen(nums) >= 1が保証されてますが、空配列だとIndexErrorになりますね。
def helper(left, right): | ||
if left > right: | ||
return None | ||
mid = (left + right) // 2 |
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.
コードからは意識してるか分からなかったので念の為共有です。範囲に含まれる要素が偶数のときに真ん中が存在しないのでmidの選択により左と右のどちらをrootにするかが決まりますね。
問題
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/