File tree Expand file tree Collapse file tree 2 files changed +64
-3
lines changed Expand file tree Collapse file tree 2 files changed +64
-3
lines changed Original file line number Diff line number Diff line change @@ -344,6 +344,48 @@ class Solution:
344
344
return root
345
345
```
346
346
347
+ ** 迭代法**
348
+ ``` python
349
+ class Solution :
350
+ def deleteNode (self , root : Optional[TreeNode], key : int ) -> Optional[TreeNode]:
351
+ # 找到节点后分两步,1. 把节点的左子树和右子树连起来,2. 把右子树跟父节点连起来
352
+ # root is None
353
+ if not root: return root
354
+ p = root
355
+ last = None
356
+ while p:
357
+ if p.val== key:
358
+ # 1. connect left to right
359
+ # right is not None -> left is None | left is not None
360
+ if p.right:
361
+ if p.left:
362
+ node = p.right
363
+ while node.left:
364
+ node = node.left
365
+ node.left = p.left
366
+ right = p.right
367
+ else :
368
+ # right is None -> right=left
369
+ right = p.left
370
+ # 2. connect right to last
371
+ if last== None :
372
+ root = right
373
+ elif last.val> key:
374
+ last.left = right
375
+ else :
376
+ last.right = right
377
+ # 3. return
378
+ break
379
+ else :
380
+ # Update last and continue
381
+ last = p
382
+ if p.val> key:
383
+ p = p.left
384
+ else :
385
+ p = p.right
386
+ return root
387
+ ```
388
+
347
389
## Go
348
390
``` Go
349
391
// 递归版本
Original file line number Diff line number Diff line change @@ -330,23 +330,42 @@ class Solution:
330
330
return root
331
331
```
332
332
333
+ ** 递归法** - 无返回值 有注释 不用Helper function
334
+ ``` python
335
+ class Solution :
336
+ def insertIntoBST (self , root : Optional[TreeNode], val : int ) -> Optional[TreeNode]:
337
+ if not root: # for root==None
338
+ return TreeNode(val)
339
+ if root.val< val:
340
+ if root.right== None : # find the parent
341
+ root.right = TreeNode(val)
342
+ else : # not found, keep searching
343
+ self .insertIntoBST(root.right, val)
344
+ if root.val> val:
345
+ if root.left== None : # found the parent
346
+ root.left = TreeNode(val)
347
+ else : # not found, keep searching
348
+ self .insertIntoBST(root.left, val)
349
+ # return the final tree
350
+ return root
351
+ ```
352
+
333
353
** 迭代法**
334
354
与无返回值的递归函数的思路大体一致
335
355
``` python
336
356
class Solution :
337
357
def insertIntoBST (self , root : TreeNode, val : int ) -> TreeNode:
338
358
if not root:
339
359
return TreeNode(val)
340
- parent = None
360
+ parent = None # 此步可以省略
341
361
cur = root
342
362
343
363
# 用while循环不断地找新节点的parent
344
364
while cur:
365
+ parent = cur # 首先保存当前非空节点作为下一次迭代的父节点
345
366
if cur.val < val:
346
- parent = cur
347
367
cur = cur.right
348
368
elif cur.val > val:
349
- parent = cur
350
369
cur = cur.left
351
370
352
371
# 运行到这意味着已经跳出上面的while循环,
You can’t perform that action at this time.
0 commit comments