思路:
因为是二叉搜索树,所以根节点比左节点大,比右节点小。用递归比较两边节点的元素,如果节点大于该元素向左遍历,小于该元素向右遍历。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root == NULL || root ->val == val) return root;
TreeNode *node = NULL;
if(root -> val > val) return node = searchBST(root ->left,val);
if(root -> val < val) return node = searchBST(root ->right,val);
return node;
}
};