Skip to content

108. Convert Sorted Array to Binary Search Tree#23

Open
hroc135 wants to merge 4 commits intomainfrom
108ConvertSortedArrayUtoBinarySearchTree
Open

108. Convert Sorted Array to Binary Search Tree#23
hroc135 wants to merge 4 commits intomainfrom
108ConvertSortedArrayUtoBinarySearchTree

Conversation

@hroc135
Copy link
Copy Markdown
Owner

@hroc135 hroc135 commented Oct 12, 2024


#### 2c ヘルパーなし再帰
- 参考: https://github.com/SuperHotDogCat/coding-interview/pull/40/files#diff-1018f02b072a5def763a050d7e7a2d269bddcf6a7e6fb830d1fd1f768e7a1f61R8
- なんだそれでできるのかと感動。自分で思いつきたかった
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

これ、要するに再帰をある種の分業だと思ったときに、どこまでを上がやってどこからを下がやるかの境目の調整をしていることに相当しているはずです。
人間が集まってこの作業を手でするとして、どういうマニュアルを書くか、どこを仕事の境界にするかに対応しているでしょう。

@TORUS0818
Copy link
Copy Markdown

先に木を作ってからin-orderで埋めていく方法もあります。
in-orderが苦手なら練習になるかもです。

ご参考:
(言語違ってすみません)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
        # complete binary tree
        def build_cbt(index: int):
            if index >= len(nums):
                return None
            root = TreeNode()
            root.left = build_cbt(2 * index + 1)
            root.right = build_cbt(2 * index + 2)
            return root
        
        nums_queue = deque(nums)
        def set_values(cbt_root: Optional[TreeNode]) -> None:
            if not cbt_root:
                return None
            set_values(cbt_root.left)
            cbt_root.val = nums_queue.popleft()
            set_values(cbt_root.right)

        cbt_root = build_cbt(0)
        set_values(cbt_root)

        return cbt_root

@hroc135
Copy link
Copy Markdown
Owner Author

hroc135 commented Oct 20, 2024

@TORUS0818
in-order知らなかったので、非常に勉強になりました
2ab0593で実装してみました

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