File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change @@ -352,6 +352,38 @@ class Solution:
352
352
return mid_root
353
353
```
354
354
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
+
355
387
## Go
356
388
357
389
递归(隐含回溯)
You can’t perform that action at this time.
0 commit comments