思路
观察法
二叉搜索树的搜索操作,比较根节点的数值,
- 如果等于:找到了;
- 大于根节点:在右子树,往右走;
- 小于根节点:在左子树,往左走;
代码
/**
* 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* result;
void travel(TreeNode* root, int val)
{
if(root == NULL)
{
return;
}
if(root->val == val)
{
result = root;
return;
}
else if(root->val < val)
{
searchBST(root->right, val);
}
else
{
searchBST(root->left, val);
}
}
TreeNode* searchBST(TreeNode* root, int val)
{
travel(root, val);
return result;
}
};