Merge pull request #1693 from roylx/master

0701.二叉搜索树中的插入操作 - 优化了Python3 迭代法 和 增加了 Python3 递归法 - 无返回值 0450.删除二叉搜索树中的节点 - 添加python3迭代法
This commit is contained in:
程序员Carl
2022-10-18 10:16:23 +08:00
committed by GitHub
2 changed files with 64 additions and 3 deletions

View File

@@ -330,6 +330,26 @@ class Solution:
return root
```
**递归法** - 无返回值 有注释 不用Helper function
```python
class Solution:
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
if not root: # for root==None
return TreeNode(val)
if root.val<val:
if root.right==None: # find the parent
root.right = TreeNode(val)
else: # not found, keep searching
self.insertIntoBST(root.right, val)
if root.val>val:
if root.left==None: # found the parent
root.left = TreeNode(val)
else: # not found, keep searching
self.insertIntoBST(root.left, val)
# return the final tree
return root
```
**迭代法**
与无返回值的递归函数的思路大体一致
```python
@@ -337,16 +357,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循环,