Find the node in the BST that the node’s value equals val
and return the subtree rooted with that node. If such a node does not exist, return null
.
Example 1:
Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]
Example 2:
Input: root = [4,2,7,1,3], val = 5
Output: []
Constraints:
-
The number of nodes in the tree is in the range [ 1 , 5000 ] [1, 5000] [1,5000].
-
1 < = N o d e . v a l < = 1 0 7 1 <= Node.val <= 10^7 1<=Node.val<=107
-
root
is a binary search tree. -
1 < = v a l < = 1 0 7 1 <= val <= 10^7 1<=val<=107
方法一:递归法
方法二:迭代法
import com.lun.util.BinaryTree.TreeNode;
public class SearchInABinarySearchTree {
//方法一:递归法
public TreeNode searchBST(TreeNode root, int val) {
if(root == null) return null;
if(val < root.val)
return searchBST(root.left, val);
else if(root.val < val)
return searchBST(root.right, val);
else
return root;
}
//方法二:迭代法
public TreeNode searchBST2(TreeNode root, int val) {
TreeNode p = root;
while(p != null) {
if(val < p.val) {
p = p.left;
}else if(val > p.val){
p = p.right;
}else {
return p;
}
}
return null;
}
}
import static org.junit.Assert.*;
import org.junit.Test;
import com.lun.util.BinaryTree;
import com.lun.util.BinaryTree.TreeNode;