Open
Conversation
oda
reviewed
Oct 12, 2024
|
|
||
| #### 2c ヘルパーなし再帰 | ||
| - 参考: https://github.com/SuperHotDogCat/coding-interview/pull/40/files#diff-1018f02b072a5def763a050d7e7a2d269bddcf6a7e6fb830d1fd1f768e7a1f61R8 | ||
| - なんだそれでできるのかと感動。自分で思いつきたかった |
There was a problem hiding this comment.
これ、要するに再帰をある種の分業だと思ったときに、どこまでを上がやってどこからを下がやるかの境目の調整をしていることに相当しているはずです。
人間が集まってこの作業を手でするとして、どういうマニュアルを書くか、どこを仕事の境界にするかに対応しているでしょう。
|
先に木を作ってから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 |
Owner
Author
|
@TORUS0818 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/description/