We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent af5ce7d commit 8dc9109Copy full SHA for 8dc9109
problems/0701.二叉搜索树中的插入操作.md
@@ -370,6 +370,30 @@ class Solution:
370
371
372
```
373
+
374
+迭代法(精简)
375
+```python
376
+class Solution:
377
+ def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
378
+ if not root: # 如果根节点为空,创建新节点作为根节点并返回
379
+ return TreeNode(val)
380
+ cur = root
381
+ while cur:
382
+ if val < cur.val:
383
+ if not cur.left: # 如果此时父节点的左子树为空
384
+ cur.left = TreeNode(val) # 将新节点连接到父节点的左子树
385
+ return root
386
+ else:
387
+ cur = cur.left
388
+ elif val > cur.val:
389
+ if not cur.right: # 如果此时父节点的左子树为空
390
+ cur.right = TreeNode(val) # 将新节点连接到父节点的右子树
391
392
393
+ cur = cur.right
394
395
+```
396
397
-----
398
### Go
399
0 commit comments