1,题目要求
Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node’s value equals the given value. Return the subtree rooted with that node. If such node doesn’t exist, you should return NULL.
找到BST中的对应值的节点的子树。
2,题目思路
对于一个BST,因为是已经有大小的次序,而找到子树实际上就是找到对应值的节点而已,因此直接对子树进行遍历(二分查找即可)
3,程序源码
写法1:
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
while(root)
{
if(root->val == val) return root;
else if(root->val > val) return searchBST(root->left, val);
else return searchBST(root->right, val);
}
return nullptr;
}
};
写法2:
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root == nullptr) return nullptr;
if(root->val == val) return root;
else if(root->val > val) return searchBST(root->left, val);
else return searchBST(root->right, val);
}
};