Skip to content

Commit 7c9b56c

Browse files
update: 添加问题“669. 修剪二叉搜索树”的Java版代码 (#1186)
* 添加669. 修剪二叉搜索树的Java版代码 * refactor: format Java code * docs: acknowledgement (#1186) * docs: typo --------- Co-authored-by: LetMeFly666 <[email protected]>
1 parent f119648 commit 7c9b56c

File tree

2 files changed

+65
-1
lines changed

2 files changed

+65
-1
lines changed
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*
2+
* @Author: laughWinter
3+
* @Date: 2025-10-26 23:16:50
4+
* @LastEditors: LetMeFly.xyz
5+
* @LastEditTime: 2025-10-27 09:42:30
6+
*/
7+
// import javax.swing.tree.TreeNode;
8+
9+
/**
10+
* Definition for a binary tree node.
11+
* public class TreeNode {
12+
* int val;
13+
* TreeNode left;
14+
* TreeNode right;
15+
* TreeNode() {}
16+
* TreeNode(int val) { this.val = val; }
17+
* TreeNode(int val, TreeNode left, TreeNode right) {
18+
* this.val = val;
19+
* this.left = left;
20+
* this.right = right;
21+
* }
22+
* }
23+
*/
24+
25+
class Solution {
26+
public TreeNode trimBST(TreeNode root, int low, int high) {
27+
//寻找新的根节点
28+
while ((root != null) && ((root.val < low) || (root.val > high))) {
29+
if (root.val < low) {
30+
root = root.right;
31+
} else if (root.val > high) {
32+
root = root.left;
33+
}
34+
}
35+
if (root == null) {
36+
return null;
37+
}
38+
//修建root的左右子树
39+
TreeNode tmp = root;
40+
while (tmp.left != null) {
41+
if (tmp.left.val < low) {
42+
tmp.left = tmp.left.right;
43+
} else {
44+
tmp = tmp.left;
45+
}
46+
}
47+
tmp = root;
48+
while (tmp.right != null) {
49+
if (tmp.right.val > high) {
50+
tmp.right = tmp.right.left;
51+
} else {
52+
tmp = tmp.right;
53+
}
54+
}
55+
56+
return root;
57+
}
58+
}

README.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
* @Author: LetMeFly
33
* @Date: 2022-05-19 18:48:53
44
* @LastEditors: LetMeFly.xyz
5-
* @LastEditTime: 2025-09-27 13:24:44
5+
* @LastEditTime: 2025-10-27 10:03:05
66
-->
77
# LetLeet Blog
88

@@ -33,6 +33,12 @@
3333

3434
在线博客:[blog.letmefly.xyz](https://blog.letmefly.xyz/)
3535

36+
真诚感谢本仓库的贡献者!
37+
38+
|贡献者|贡献内容|
39+
|:--:|:--:|
40+
|[laughWinter](https://github.com/laughWinter)|添加LeetCode669.Java版本的代码[#1186](https://github.com/LetMeFly666/LeetCode/pull/1186)|
41+
3642
## 技术思考
3743

3844
|名称|博客|CSDN博客地址|

0 commit comments

Comments
 (0)