LeetCode 700. Search in a Binary Search Tree
You are given the root of a binary search tree (BST) and an integer val.
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.
Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]
method: 递归
递归结束条件:如果节点为空,说明没找到,返回空节点;如果等于val
,说明找到,也返回当前节点
单层逻辑:当前节点值比val
大,往左子树找,比val
小,往右子树找
TreeNode* searchBST(TreeNode* root, int val) {
if (!root || root->val == val) return root;
if (root->val > val) return searchBST(root->left, val);
else return searchBST(root->right, val);
}