二叉搜索树查找
该题是数据结构课中二叉搜索数(BST)的查找的一个操作。
二叉搜索树的特点:
每个节点的值都比左子树任何一个节点的值大,都比右子树任何一个节点小
从root开始遍历
若$target == now$,则说明已经找到了以target为根的子树,返回即可
若$target[HTML_REMOVED]target,则一定不在now的右子树,则now = now->left
否则,说明now一定在now的左子树里面
都找不到最终now会变成空,返回即可。
时间复杂度$O(N)$
AC代码
/**
* 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 target) {
while (root) {
if (root->val == target) return root;
else if (root->val < target) root = root->right;
else root = root->left;
}
return root;
}
};