parent
beeff54cc1
commit
7d8e9e8fae
|
|
@ -310,6 +310,26 @@ class Solution:
|
||||||
return root
|
return root
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**递归法** - 无返回值 - another easier way
|
||||||
|
```python
|
||||||
|
class Solution:
|
||||||
|
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
|
||||||
|
newNode = TreeNode(val)
|
||||||
|
if not root: return newNode
|
||||||
|
|
||||||
|
if not root.left and val < root.val:
|
||||||
|
root.left = newNode
|
||||||
|
if not root.right and val > root.val:
|
||||||
|
root.right = newNode
|
||||||
|
|
||||||
|
if val < root.val:
|
||||||
|
self.insertIntoBST(root.left, val)
|
||||||
|
if val > root.val:
|
||||||
|
self.insertIntoBST(root.right, val)
|
||||||
|
|
||||||
|
return root
|
||||||
|
```
|
||||||
|
|
||||||
**迭代法**
|
**迭代法**
|
||||||
与无返回值的递归函数的思路大体一致
|
与无返回值的递归函数的思路大体一致
|
||||||
```python
|
```python
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue