diff --git a/problems/0701.二叉搜索树中的插入操作.md b/problems/0701.二叉搜索树中的插入操作.md index 468f2675..5e9fbdfe 100644 --- a/problems/0701.二叉搜索树中的插入操作.md +++ b/problems/0701.二叉搜索树中的插入操作.md @@ -310,6 +310,26 @@ class Solution: 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