Skip to content

Commit 59d7c5d

Browse files
committed
669. 修剪二叉搜索树
1 parent c3d06d9 commit 59d7c5d

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@
143143
|645|[错误的集合](https://leetcode.cn/problems/set-mismatch/)|[JavaScript](./algorithms/set-mismatch.js)|Easy|
144144
|654|[最大二叉树](https://leetcode.cn/problems/maximum-binary-tree/)|[JavaScript](./algorithms/maximum-binary-tree.js)|Medium|
145145
|657|[机器人能否返回原点](https://leetcode.cn/problems/robot-return-to-origin/)|[JavaScript](./algorithms/robot-return-to-origin.js)|Easy|
146+
|669|[修剪二叉搜索树](https://leetcode.cn/problems/trim-a-binary-search-tree/)|[JavaScript](./algorithms/trim-a-binary-search-tree.js)|Medium|
146147
|682|[棒球比赛](https://leetcode.cn/problems/baseball-game/)|[JavaScript](./algorithms/baseball-game.js)|Easy|
147148
|687|[最长同值路径](https://leetcode.cn/problems/longest-univalue-path/)|[JavaScript](./algorithms/longest-univalue-path.js)|Medium|
148149
|700|[二叉搜索树中的搜索](https://leetcode.cn/problems/search-in-a-binary-search-tree/)|[JavaScript](./algorithms/search-in-a-binary-search-tree.js)|Easy|
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {TreeNode} root
11+
* @param {number} low
12+
* @param {number} high
13+
* @return {TreeNode}
14+
*/
15+
var trimBST = function (root, low, high) {
16+
// 后序遍历
17+
if (!root) return null;
18+
root.left = trimBST(root.left, low, high);
19+
root.right = trimBST(root.right, low, high);
20+
if (root.val < low || root.val > high) {
21+
// 叶节点
22+
if (!root.left && !root.right) {
23+
return null;
24+
}
25+
// 左节点不存在
26+
if (!root.left) {
27+
return root.right;
28+
}
29+
// 右节点不存在
30+
if (!root.right) {
31+
return root.left;
32+
}
33+
}
34+
return root;
35+
};

0 commit comments

Comments
 (0)