Skip to content

Commit

Permalink
Merge branch 'master' of github.com:KingArthur0205/leetcode-master
Browse files Browse the repository at this point in the history
  • Loading branch information
KingArthur0205 committed Jan 26, 2023
2 parents 9d02c76 + fdfa50b commit b7c8ba8
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
32 changes: 32 additions & 0 deletions problems/0108.将有序数组转换为二叉搜索树.md
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,38 @@ class Solution:
return mid_root
```

**迭代**(左闭右开)
```python
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
if len(nums) == 0: return None
root = TreeNode() # 初始化
nodeSt = [root]
leftSt = [0]
rightSt = [len(nums)]

while nodeSt:
node = nodeSt.pop() # 处理根节点
left = leftSt.pop()
right = rightSt.pop()
mid = left + (right - left) // 2
node.val = nums[mid]

if left < mid: # 处理左区间
node.left = TreeNode()
nodeSt.append(node.left)
leftSt.append(left)
rightSt.append(mid)

if right > mid + 1: # 处理右区间
node.right = TreeNode()
nodeSt.append(node.right)
leftSt.append(mid + 1)
rightSt.append(right)

return root
```

## Go

递归(隐含回溯)
Expand Down
18 changes: 18 additions & 0 deletions problems/0450.删除二叉搜索树中的节点.md
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,24 @@ class Solution:
return root
```

**普通二叉树的删除方式**
```python
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if not root: return root
if root.val == key:
if not root.right: # 这里第二次操作目标值:最终删除的作用
return root.left
tmp = root.right
while tmp.left:
tmp = tmp.left
root.val, tmp.val = tmp.val, root.val # 这里第一次操作目标值:交换目标值其右子树最左面节点。

root.left = self.deleteNode(root.left, key)
root.right = self.deleteNode(root.right, key)
return root
```

**迭代法**
```python
class Solution:
Expand Down
26 changes: 26 additions & 0 deletions problems/0669.修剪二叉搜索树.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,32 @@ class Solution:
return root
```

**迭代**
```python
class Solution:
def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
if not root: return root
# 处理头结点,让root移动到[L, R] 范围内,注意是左闭右开
while root and (root.val < low or root.val > high):
if root.val < low: # 小于L往右走
root = root.right
else: # 大于R往左走
root = root.left
# 此时root已经在[L, R] 范围内,处理左孩子元素小于L的情况
cur = root
while cur:
while cur.left and cur.left.val < low:
cur.left = cur.left.right
cur = cur.left
# 此时root已经在[L, R] 范围内,处理右孩子大于R的情况
cur = root
while cur:
while cur.right and cur.right.val > high:
cur.right = cur.right.left
cur = cur.right
return root
```

## Go

```go
Expand Down

0 comments on commit b7c8ba8

Please sign in to comment.