Merge pull request #562 from KelvinG-611/701.二叉搜索树中的插入操作

更新701.二叉搜索树中的插入操作 Python3 版本
This commit is contained in:
程序员Carl
2021-08-06 10:09:24 +08:00
committed by GitHub

View File

@ -255,7 +255,7 @@ class Solution {
Python
递归法
**递归法** - 有返回值
```python
class Solution:
@ -268,7 +268,63 @@ class Solution:
root.left = self.insertIntoBST(root.left, val) # 递归创建左子树
return root
```
**递归法** - 无返回值
```python
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
parent = None
def __traverse(cur: TreeNode, val: int) -> None:
# 在函数运行的同时把新节点插入到该被插入的地方.
nonlocal parent
if not cur:
new_node = TreeNode(val)
if parent.val < val:
parent.right = new_node
else:
parent.left = new_node
return
parent = cur # 重点: parent的作用只有运行到上面if not cur:才会发挥出来.
if cur.val < val:
__traverse(cur.right, val)
else:
__traverse(cur.left, val)
return
__traverse(root, val)
return root
```
**迭代法**
与无返回值的递归函数的思路大体一致
```python
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
parent = None
cur = root
# 用while循环不断地找新节点的parent
while cur:
if cur.val < val:
parent = cur
cur = cur.right
elif cur.val > val:
parent = cur
cur = cur.left
# 运行到这意味着已经跳出上面的while循环,
# 同时意味着新节点的parent已经被找到.
# parent已被找到, 新节点已经ready. 把两个节点黏在一起就好了.
if parent.val > val:
parent.left = TreeNode(val)
else:
parent.right = TreeNode(val)
return root
```
Go