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

Commit 5cbb991

Browse files
Merge pull request youngyangyang04#2072 from Lozakaka/patch-8
adding java iteration method
2 parents eb91a26 + c76ed37 commit 5cbb991

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

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

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,8 @@ public:
248248

249249
## Java
250250

251+
**递归**
252+
251253
```Java
252254
class Solution {
253255
public TreeNode trimBST(TreeNode root, int low, int high) {
@@ -269,6 +271,46 @@ class Solution {
269271

270272
```
271273

274+
**迭代**
275+
276+
```Java
277+
class Solution {
278+
//iteration
279+
public TreeNode trimBST(TreeNode root, int low, int high) {
280+
if(root == null)
281+
return null;
282+
while(root != null && (root.val < low || root.val > high)){
283+
if(root.val < low)
284+
root = root.right;
285+
else
286+
root = root.left;
287+
}
288+
289+
TreeNode curr = root;
290+
291+
//deal with root's left sub-tree, and deal with the value smaller than low.
292+
while(curr != null){
293+
while(curr.left != null && curr.left.val < low){
294+
curr.left = curr.left.right;
295+
}
296+
curr = curr.left;
297+
}
298+
//go back to root;
299+
curr = root;
300+
301+
//deal with root's righg sub-tree, and deal with the value bigger than high.
302+
while(curr != null){
303+
while(curr.right != null && curr.right.val > high){
304+
curr.right = curr.right.left;
305+
}
306+
curr = curr.right;
307+
}
308+
return root;
309+
}
310+
}
311+
312+
````
313+
272314
## Python
273315

274316
递归法(版本一)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /