Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions problems/0669.修剪二叉搜索树.md
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,56 @@ var trimBST = function (root,low,high) {
}
```

## TypeScript

> 递归法

```typescript
function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null {
if (root === null) return null;
if (root.val < low) {
return trimBST(root.right, low, high);
}
if (root.val > high) {
return trimBST(root.left, low, high);
}
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
};
```

> 迭代法

```typescript
function trimBST(root: TreeNode | null, low: number, high: number): TreeNode | null {
while (root !== null && (root.val < low || root.val > high)) {
if (root.val < low) {
root = root.right;
} else if (root.val > high) {
root = root.left;
}
}
let curNode: TreeNode | null = root;
while (curNode !== null) {
while (curNode.left !== null && curNode.left.val < low) {
curNode.left = curNode.left.right;
}
curNode = curNode.left;
}
curNode = root;
while (curNode !== null) {
while (curNode.right !== null && curNode.right.val > high) {
curNode.right = curNode.right.left;
}
curNode = curNode.right;
}
return root;
};
```




-----------------------
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>