Skip to content

Commit cd1c56a

Browse files
authored
Update 0701.二叉搜索树中的插入操作.md
补充python注释
1 parent 145b5b0 commit cd1c56a

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

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

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -253,21 +253,38 @@ class Solution {
253253
}
254254
}
255255
```
256-
256+
-----
257257
## Python
258258

259259
**递归法** - 有返回值
260260

261261
```python
262+
# Definition for a binary tree node.
263+
# class TreeNode:
264+
# def __init__(self, val=0, left=None, right=None):
265+
# self.val = val
266+
# self.left = left
267+
# self.right = right
262268
class Solution:
263269
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
264-
if root is None:
265-
return TreeNode(val) # 如果当前节点为空,也就意味着val找到了合适的位置,此时创建节点直接返回。
270+
# 返回更新后的以当前root为根节点的新树,方便用于更新上一层的父子节点关系链
271+
272+
# Base Case
273+
if not root: return TreeNode(val)
274+
275+
# 单层递归逻辑:
276+
if val < root.val:
277+
# 将val插入至当前root的左子树中合适的位置
278+
# 并更新当前root的左子树为包含目标val的新左子树
279+
root.left = self.insertIntoBST(root.left, val)
280+
266281
if root.val < val:
267-
root.right = self.insertIntoBST(root.right, val) # 递归创建右子树
268-
if root.val > val:
269-
root.left = self.insertIntoBST(root.left, val) # 递归创建左子树
270-
return root
282+
# 将val插入至当前root的右子树中合适的位置
283+
# 并更新当前root的右子树为包含目标val的新右子树
284+
root.right = self.insertIntoBST(root.right, val)
285+
286+
# 返回更新后的以当前root为根节点的新树
287+
return roo
271288
```
272289

273290
**递归法** - 无返回值
@@ -328,7 +345,7 @@ class Solution:
328345
return root
329346

330347
```
331-
348+
-----
332349
## Go
333350

334351
递归法
@@ -374,7 +391,7 @@ func insertIntoBST(root *TreeNode, val int) *TreeNode {
374391
return root
375392
}
376393
```
377-
394+
-----
378395
## JavaScript
379396

380397
有返回值的递归写法

0 commit comments

Comments
 (0)