Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2072 from Lozakaka/patch-8
Browse files Browse the repository at this point in the history
adding java iteration method
  • Loading branch information
youngyangyang04 authored May 27, 2023
2 parents eb91a26 + c76ed37 commit 5cbb991
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions problems/0669.修剪二叉搜索树.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,8 @@ public:

## Java

**递归**

```Java
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
Expand All @@ -269,6 +271,46 @@ class Solution {

```

**迭代**

```Java
class Solution {
//iteration
public TreeNode trimBST(TreeNode root, int low, int high) {
if(root == null)
return null;
while(root != null && (root.val < low || root.val > high)){
if(root.val < low)
root = root.right;
else
root = root.left;
}

TreeNode curr = root;

//deal with root's left sub-tree, and deal with the value smaller than low.
while(curr != null){
while(curr.left != null && curr.left.val < low){
curr.left = curr.left.right;
}
curr = curr.left;
}
//go back to root;
curr = root;

//deal with root's righg sub-tree, and deal with the value bigger than high.
while(curr != null){
while(curr.right != null && curr.right.val > high){
curr.right = curr.right.left;
}
curr = curr.right;
}
return root;
}
}

````

## Python

递归法(版本一)
Expand Down

0 comments on commit 5cbb991

Please sign in to comment.