File tree Expand file tree Collapse file tree 1 file changed +26
-9
lines changed Expand file tree Collapse file tree 1 file changed +26
-9
lines changed Original file line number Diff line number Diff line change @@ -253,21 +253,38 @@ class Solution {
253
253
}
254
254
}
255
255
```
256
-
256
+ -----
257
257
## Python
258
258
259
259
** 递归法** - 有返回值
260
260
261
261
``` 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
262
268
class Solution :
263
269
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
+
266
281
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
271
288
```
272
289
273
290
** 递归法** - 无返回值
@@ -328,7 +345,7 @@ class Solution:
328
345
return root
329
346
330
347
```
331
-
348
+ -----
332
349
## Go
333
350
334
351
递归法
@@ -374,7 +391,7 @@ func insertIntoBST(root *TreeNode, val int) *TreeNode {
374
391
return root
375
392
}
376
393
```
377
-
394
+ -----
378
395
## JavaScript
379
396
380
397
有返回值的递归写法
You can’t perform that action at this time.
0 commit comments