給定二叉搜索樹(BST)的根節點 root 和一個整數值 val。
你需要在 BST 中找到節點值等於 val 的節點。 返回以該節點爲根的子樹。 如果節點不存在,則返回 null 。
示例 1:
輸入:root = [4,2,7,1,3], val = 2
輸出:[2,1,3]
示例 2:
輸入:root = [4,2,7,1,3], val = 5
輸出:[]
提示:
數中節點數在 [1, 5000] 範圍內
1 <= Node.val <= 107
root 是二叉搜索樹
1 <= val <= 107
Related Topics
思路:二叉搜索樹可以採用二分法查找
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode searchBST(TreeNode root, int val) {
if (root == null) {
return null;
}
if (val < root.val) {
return searchBST(root.left, val);
} else if (val > root.val) {
return searchBST(root.right, val);
}
return root;
}
}
//leetcode submit region end(Prohibit modification and deletion)