Skip to content

108. Convert Sorted Array to Binary Search Tree#29

Open
hayashi-ay wants to merge 3 commits intomainfrom
hayashi-ay-patch-18
Open

108. Convert Sorted Array to Binary Search Tree#29
hayashi-ay wants to merge 3 commits intomainfrom
hayashi-ay-patch-18

Conversation

@hayashi-ay
Copy link
Copy Markdown
Owner

@shining-ai
Copy link
Copy Markdown

どのコードも読みやすかったです。
コメントは特にないです。

return make_bst(nums, 0, len(nums))
```

ループでも解いてみた。dequeを使っても良い。二分木はリストと違ってSentinelノードを使えない。再帰の方が楽。
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

(読みやすいかは別にして)このようにできませんか?

sentinel = TreeNode(float('inf'), 0, len(nums) - 1)
...
return sentinel.left

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.

あー、たしかにできますね。二分木でも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

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.

3 participants