给定二叉搜索树(BST)的根节点 root 和一个整数值 val

你需要在 BST 中找到节点值等于 val 的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 null 。

示例 1:

https://assets.leetcode.com/uploads/2021/01/12/tree1.jpg

输入:root = [4,2,7,1,3], val = 2
输出:[2,1,3]

示例 2:

https://assets.leetcode.com/uploads/2021/01/12/tree2.jpg

输入:root = [4,2,7,1,3], val = 5
输出:[]

提示:

/**
 * 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;
        }
        else if (root.val == val ){
            return root;
        }
        else if (root.val < val){
            root = searchBST(root.right, val);
        }
        else if (root.val > val){
           root = searchBST(root.left, val);
        }
        return root;
    }
}

二分查找