mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Update 0108.将有序数组转换为二叉搜索树.md 添加迭代法python3代码
This commit is contained in:
@ -352,6 +352,38 @@ class Solution:
|
||||
return mid_root
|
||||
```
|
||||
|
||||
**迭代**(左闭右开)
|
||||
```python
|
||||
class Solution:
|
||||
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
|
||||
if len(nums) == 0: return None
|
||||
root = TreeNode() # 初始化
|
||||
nodeSt = [root]
|
||||
leftSt = [0]
|
||||
rightSt = [len(nums)]
|
||||
|
||||
while nodeSt:
|
||||
node = nodeSt.pop() # 处理根节点
|
||||
left = leftSt.pop()
|
||||
right = rightSt.pop()
|
||||
mid = left + (right - left) // 2
|
||||
node.val = nums[mid]
|
||||
|
||||
if left < mid: # 处理左区间
|
||||
node.left = TreeNode()
|
||||
nodeSt.append(node.left)
|
||||
leftSt.append(left)
|
||||
rightSt.append(mid)
|
||||
|
||||
if right > mid + 1: # 处理右区间
|
||||
node.right = TreeNode()
|
||||
nodeSt.append(node.right)
|
||||
leftSt.append(mid + 1)
|
||||
rightSt.append(right)
|
||||
|
||||
return root
|
||||
```
|
||||
|
||||
## Go
|
||||
|
||||
递归(隐含回溯)
|
||||
|
Reference in New Issue
Block a user