mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
Merge pull request #1693 from roylx/master
0701.二叉搜索树中的插入操作 - 优化了Python3 迭代法 和 增加了 Python3 递归法 - 无返回值 0450.删除二叉搜索树中的节点 - 添加python3迭代法
This commit is contained in:
@ -344,6 +344,48 @@ class Solution:
|
||||
return root
|
||||
```
|
||||
|
||||
**迭代法**
|
||||
```python
|
||||
class Solution:
|
||||
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
|
||||
# 找到节点后分两步,1. 把节点的左子树和右子树连起来,2. 把右子树跟父节点连起来
|
||||
# root is None
|
||||
if not root: return root
|
||||
p = root
|
||||
last = None
|
||||
while p:
|
||||
if p.val==key:
|
||||
# 1. connect left to right
|
||||
# right is not None -> left is None | left is not None
|
||||
if p.right:
|
||||
if p.left:
|
||||
node = p.right
|
||||
while node.left:
|
||||
node = node.left
|
||||
node.left = p.left
|
||||
right = p.right
|
||||
else:
|
||||
# right is None -> right=left
|
||||
right = p.left
|
||||
# 2. connect right to last
|
||||
if last==None:
|
||||
root = right
|
||||
elif last.val>key:
|
||||
last.left = right
|
||||
else:
|
||||
last.right = right
|
||||
# 3. return
|
||||
break
|
||||
else:
|
||||
# Update last and continue
|
||||
last = p
|
||||
if p.val>key:
|
||||
p = p.left
|
||||
else:
|
||||
p = p.right
|
||||
return root
|
||||
```
|
||||
|
||||
## Go
|
||||
```Go
|
||||
// 递归版本
|
||||
|
@ -330,6 +330,26 @@ class Solution:
|
||||
return root
|
||||
```
|
||||
|
||||
**递归法** - 无返回值 有注释 不用Helper function
|
||||
```python
|
||||
class Solution:
|
||||
def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
|
||||
if not root: # for root==None
|
||||
return TreeNode(val)
|
||||
if root.val<val:
|
||||
if root.right==None: # find the parent
|
||||
root.right = TreeNode(val)
|
||||
else: # not found, keep searching
|
||||
self.insertIntoBST(root.right, val)
|
||||
if root.val>val:
|
||||
if root.left==None: # found the parent
|
||||
root.left = TreeNode(val)
|
||||
else: # not found, keep searching
|
||||
self.insertIntoBST(root.left, val)
|
||||
# return the final tree
|
||||
return root
|
||||
```
|
||||
|
||||
**迭代法**
|
||||
与无返回值的递归函数的思路大体一致
|
||||
```python
|
||||
@ -337,16 +357,15 @@ class Solution:
|
||||
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
|
||||
if not root:
|
||||
return TreeNode(val)
|
||||
parent = None
|
||||
parent = None # 此步可以省略
|
||||
cur = root
|
||||
|
||||
# 用while循环不断地找新节点的parent
|
||||
while cur:
|
||||
parent = cur # 首先保存当前非空节点作为下一次迭代的父节点
|
||||
if cur.val < val:
|
||||
parent = cur
|
||||
cur = cur.right
|
||||
elif cur.val > val:
|
||||
parent = cur
|
||||
cur = cur.left
|
||||
|
||||
# 运行到这意味着已经跳出上面的while循环,
|
||||
|
Reference in New Issue
Block a user