mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
Merge pull request #2072 from Lozakaka/patch-8
adding java iteration method
This commit is contained in:
@ -248,6 +248,8 @@ public:
|
|||||||
|
|
||||||
## Java
|
## Java
|
||||||
|
|
||||||
|
**递归**
|
||||||
|
|
||||||
```Java
|
```Java
|
||||||
class Solution {
|
class Solution {
|
||||||
public TreeNode trimBST(TreeNode root, int low, int high) {
|
public TreeNode trimBST(TreeNode root, int low, int high) {
|
||||||
@ -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
|
## Python
|
||||||
|
|
||||||
递归法(版本一)
|
递归法(版本一)
|
||||||
|
Reference in New Issue
Block a user