Skip to content

Commit 237728f

Browse files
Merge pull request youngyangyang04#1693 from roylx/master
0701.二叉搜索树中的插入操作 - 优化了Python3 迭代法 和 增加了 Python3 递归法 - 无返回值 0450.删除二叉搜索树中的节点 - 添加python3迭代法
2 parents f3f6cab + bd77b3b commit 237728f

File tree

2 files changed

+64
-3
lines changed

2 files changed

+64
-3
lines changed

problems/0450.删除二叉搜索树中的节点.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,48 @@ class Solution:
344344
return root
345345
```
346346

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+
347389
## Go
348390
```Go
349391
// 递归版本

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

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -330,23 +330,42 @@ class Solution:
330330
return root
331331
```
332332

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+
333353
**迭代法**
334354
与无返回值的递归函数的思路大体一致
335355
```python
336356
class Solution:
337357
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
338358
if not root:
339359
return TreeNode(val)
340-
parent = None
360+
parent = None # 此步可以省略
341361
cur = root
342362

343363
# 用while循环不断地找新节点的parent
344364
while cur:
365+
parent = cur # 首先保存当前非空节点作为下一次迭代的父节点
345366
if cur.val < val:
346-
parent = cur
347367
cur = cur.right
348368
elif cur.val > val:
349-
parent = cur
350369
cur = cur.left
351370

352371
# 运行到这意味着已经跳出上面的while循环,

0 commit comments

Comments
 (0)