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

0701.二叉搜索树中的插入操作.md Python3 **递归法** - 无返回值 有注释 不用Helper function
This commit is contained in:
roylx
2022-10-12 10:34:56 -06:00
committed by GitHub
parent 12eb9158c3
commit f6db9d06e2

View File

@ -330,6 +330,27 @@ class Solution:
return root
```
**递归法** - 无返回值 有注释 不用Helper function
```
class Solution:
last = None
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