C++ 二叉查找树查找数据

查找数值value是否在二叉查找树中出现:
如果value等于当前查看node的节点值:返回真
如果value节点值小于当前node节点值:
如果当前节点有左子树,继续在左子树中查找该值;否则,返回假
否则(value节点值大于当前node节点值):
如果当前节点有右子树,继续在右子树中查找该值;否则,返回假

#include <vector>
struct TreeNode
{
 int val;
 TreeNode* left;
 TreeNode* right;
 TreeNode(int x) : val(x), left(NULL), right(NULL) {};
};
bool BST_search(TreeNode * node, int value)
{
 if (node->val==value)
 {
  return true;
 }
 if (node->val>value)
 {
  if (node->left)
  {
   BST_search(node->left, value);
  }
  else
  {
   return false;
  }
 }
 else
 {
  if (node->right)
  {
   BST_search(node->right, value);
  }
  else
  {
   return false;
  }
 }
}
int main()
{
 TreeNode a(8);
 TreeNode b(3);
 TreeNode c(10);
 TreeNode d(1);
 TreeNode e(6);
 TreeNode f(15);
 a.left = &b;
 a.right = &c;
 b.left = &d;
 b.right = &e;
 c.right = &f;
 for (int i = 0; i < 20; i++)
 {
  if (BST_search(&a, i))
  {
   printf("%d is in the BST.\n", i);
  }
  else
  {
   printf("%d is not in the BST.\n", i);
  }
 }
 return 0;
}

运行结果为:

0 is not in the BST.
1 is in the BST.
2 is not in the BST.
3 is in the BST.
4 is not in the BST.
5 is not in the BST.
6 is in the BST.
7 is not in the BST.
8 is in the BST.
9 is not in the BST.
10 is in the BST.
11 is not in the BST.
12 is not in the BST.
13 is not in the BST.
14 is not in the BST.
15 is in the BST.
16 is not in the BST.
17 is not in the BST.
18 is not in the BST.
19 is not in the BST.
发布了79 篇原创文章 · 获赞 62 · 访问量 2206

猜你喜欢

转载自blog.csdn.net/weixin_44208324/article/details/104978281
今日推荐