Skip to content

Commit b078cc2

Browse files
Merge pull request youngyangyang04#459 from xllpiupiu/master
669修剪二叉搜索树JavaScript版本
2 parents 754cb0d + 361589a commit b078cc2

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

problems/0669.修剪二叉搜索树.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,59 @@ func trimBST(root *TreeNode, low int, high int) *TreeNode {
315315
```
316316

317317

318+
JavaScript版本:
319+
迭代:
320+
```js
321+
var trimBST = function(root, low, high) {
322+
if(root === null) {
323+
return null;
324+
}
325+
while(root !==null &&(root.val<low||root.val>high)) {
326+
if(root.val<low) {
327+
root = root.right;
328+
}else {
329+
root = root.left;
330+
}
331+
}
332+
let cur = root;
333+
while(cur!==null) {
334+
while(cur.left&&cur.left.val<low) {
335+
cur.left = cur.left.right;
336+
}
337+
cur = cur.left;
338+
}
339+
cur = root;
340+
//判断右子树大于high的情况
341+
while(cur!==null) {
342+
while(cur.right&&cur.right.val>high) {
343+
cur.right = cur.right.left;
344+
}
345+
cur = cur.right;
346+
}
347+
return root;
348+
};
349+
```
350+
351+
递归:
352+
```js
353+
var trimBST = function (root,low,high) {
354+
if(root === null) {
355+
return null;
356+
}
357+
if(root.val<low) {
358+
let right = trimBST(root.right,low,high);
359+
return right;
360+
}
361+
if(root.val>high) {
362+
let left = trimBST(root.left,low,high);
363+
return left;
364+
}
365+
root.left = trimBST(root.left,low,high);
366+
root.right = trimBST(root.right,low,high);
367+
return root;
368+
}
369+
```
370+
318371

319372
-----------------------
320373
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)

0 commit comments

Comments
 (0)