Skip to content

Commit 8dc9109

Browse files
committed
修改0701.二叉搜索树中的插入操作,增加python版本的迭代法(精简)
1 parent af5ce7d commit 8dc9109

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

problems/0701.二叉搜索树中的插入操作.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,30 @@ class Solution:
370370

371371

372372
```
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+
return root
392+
else:
393+
cur = cur.right
394+
395+
```
396+
373397
-----
374398
### Go
375399

0 commit comments

Comments
 (0)