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

0701.二叉搜索树中的插入操作.md python3 迭代法优化
This commit is contained in:
roylx
2022-10-12 10:19:54 -06:00
committed by GitHub
parent 1744c21d8c
commit 12eb9158c3

View File

@ -337,16 +337,15 @@ class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
parent = None
parent = None # 此步可以省略
cur = root
# 用while循环不断地找新节点的parent
while cur:
parent = cur # 首先保存当前非空节点作为下一次迭代的父节点
if cur.val < val:
parent = cur
cur = cur.right
elif cur.val > val:
parent = cur
cur = cur.left
# 运行到这意味着已经跳出上面的while循环,