-
Notifications
You must be signed in to change notification settings - Fork 0
Solved Arai60/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
base: main
Are you sure you want to change the base?
Conversation
if middle + 1 < right: | ||
node.right = sortedArrayToBSTHelper(TreeNode(), middle + 1, right) | ||
return node | ||
return sortedArrayToBSTHelper(TreeNode(), 0, len(nums)) |
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.
TreeNode は引数で与えず中で作ってもこの場合は大丈夫でしょうかね。
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.
本当ですね。後からreturnしてくれば先につなげなくてもいいですね
while node_and_range: | ||
node, left_index, right_index = node_and_range.popleft() | ||
middle_index = (left_index + right_index) // 2 | ||
node.val = nums[middle_index] |
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.
一応、numsが空配列の場合ここでIndexErrorになりますかね。別解ではNoneを返しているので意図通りかは少し気になりました
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 = TreeNode(val=nums[0]) | ||
nodes_to_add: deque[TreeNode] = deque([root]) | ||
for i in range(1, len(nums)): | ||
node = nodes_to_add.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.
nodes_to_add という変数名で、同じノードを入れたり出したりしているのがわかりづらいと思いました。
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.
nodes_to_processとかの方が良いですかね
問題文:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/