Skip to content

Commit f963849

Browse files
authored
Update 0108.将有序数组转换为二叉搜索树.md 添加迭代法python3代码
1 parent cbc75c0 commit f963849

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

problems/0108.将有序数组转换为二叉搜索树.md

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,38 @@ class Solution:
352352
return mid_root
353353
```
354354

355+
**迭代**(左闭右开)
356+
```python
357+
class Solution:
358+
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
359+
if len(nums) == 0: return None
360+
root = TreeNode() # 初始化
361+
nodeSt = [root]
362+
leftSt = [0]
363+
rightSt = [len(nums)]
364+
365+
while nodeSt:
366+
node = nodeSt.pop() # 处理根节点
367+
left = leftSt.pop()
368+
right = rightSt.pop()
369+
mid = left + (right - left) // 2
370+
node.val = nums[mid]
371+
372+
if left < mid: # 处理左区间
373+
node.left = TreeNode()
374+
nodeSt.append(node.left)
375+
leftSt.append(left)
376+
rightSt.append(mid)
377+
378+
if right > mid + 1: # 处理右区间
379+
node.right = TreeNode()
380+
nodeSt.append(node.right)
381+
leftSt.append(mid + 1)
382+
rightSt.append(right)
383+
384+
return root
385+
```
386+
355387
## Go
356388

357389
递归(隐含回溯)

0 commit comments

Comments
 (0)