Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitb078cc2

Browse files
Merge pull requestyoungyangyang04#459 from xllpiupiu/master
669修剪二叉搜索树JavaScript版本
2 parents754cb0d +361589a commitb078cc2

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+
vartrimBST=function(root,low,high) {
322+
if(root===null) {
323+
returnnull;
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+
vartrimBST=function (root,low,high) {
354+
if(root===null) {
355+
returnnull;
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)

[8]ページ先頭

©2009-2025 Movatter.jp