mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0701.二叉搜索树中的插入操作.md
0701.二叉搜索树中的插入操作.md python3 迭代法优化
This commit is contained in:
@ -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循环,
|
||||
|
Reference in New Issue
Block a user