File tree 1 file changed +23
-27
lines changed
1 file changed +23
-27
lines changed Original file line number Diff line number Diff line change @@ -283,32 +283,10 @@ class Solution:
283
283
return TreeNode(val)
284
284
self .traversal(root, val)
285
285
return root
286
-
287
286
```
288
287
289
288
递归法(版本二)
290
289
``` python
291
- class Solution :
292
- def insertIntoBST (self , root , val ):
293
- if root is None :
294
- return TreeNode(val)
295
- parent = None
296
- cur = root
297
- while cur:
298
- parent = cur
299
- if val < cur.val:
300
- cur = cur.left
301
- else :
302
- cur = cur.right
303
- if val < parent.val:
304
- parent.left = TreeNode(val)
305
- else :
306
- parent.right = TreeNode(val)
307
- return root
308
- ```
309
-
310
- 递归法(版本三)
311
- ``` python
312
290
class Solution :
313
291
def insertIntoBST (self , root : Optional[TreeNode], val : int ) -> Optional[TreeNode]:
314
292
if root is None or root.val == val:
@@ -326,7 +304,7 @@ class Solution:
326
304
return root
327
305
```
328
306
329
- 递归法(版本四 )
307
+ 递归法(版本三 )
330
308
``` python
331
309
class Solution :
332
310
def insertIntoBST (self , root , val ):
@@ -340,10 +318,9 @@ class Solution:
340
318
root.right = self .insertIntoBST(root.right, val)
341
319
342
320
return root
343
-
344
321
```
345
322
346
- 迭代法
323
+ 迭代法(版本一)
347
324
``` python
348
325
class Solution :
349
326
def insertIntoBST (self , root , val ):
@@ -366,9 +343,28 @@ class Solution:
366
343
else :
367
344
parent.right = node # 将新节点连接到父节点的右子树
368
345
369
- return root
346
+ return root
347
+ ```
370
348
371
-
349
+ 迭代法(版本二)
350
+ ``` python
351
+ class Solution :
352
+ def insertIntoBST (self , root , val ):
353
+ if root is None :
354
+ return TreeNode(val)
355
+ parent = None
356
+ cur = root
357
+ while cur:
358
+ parent = cur
359
+ if val < cur.val:
360
+ cur = cur.left
361
+ else :
362
+ cur = cur.right
363
+ if val < parent.val:
364
+ parent.left = TreeNode(val)
365
+ else :
366
+ parent.right = TreeNode(val)
367
+ return root
372
368
```
373
369
374
370
迭代法(精简)
You can’t perform that action at this time.
0 commit comments