Skip to content

【Arai60】24問目 108_Convert Sorted Array to Binary Search Tree#24

Merged
shining-ai merged 2 commits intomainfrom
review24
Jun 30, 2024
Merged

【Arai60】24問目 108_Convert Sorted Array to Binary Search Tree#24
shining-ai merged 2 commits intomainfrom
review24

Conversation

@shining-ai
Copy link
Copy Markdown
Owner

Copy link
Copy Markdown

@hayashi-ay hayashi-ay left a 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()
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

parentとかでもいいかも。

Suggested change
node, left_range, right_range = queue.popleft()
parent, left_range, right_range = queue.popleft()

Copy link
Copy Markdown
Owner Author

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]:
Copy link
Copy Markdown

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)
Copy link
Copy Markdown

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])
Copy link
Copy Markdown

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
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

コードからは意識してるか分からなかったので念の為共有です。範囲に含まれる要素が偶数のときに真ん中が存在しないのでmidの選択により左と右のどちらをrootにするかが決まりますね。

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.

2 participants