mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Update 0701.二叉搜索树中的插入操作.md
0701.二叉搜索树中的插入操作.md Python3 **递归法** - 无返回值 有注释 不用Helper function
This commit is contained in:
@ -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
|
||||
|
Reference in New Issue
Block a user