[C++] 是否完全二叉搜索树 →→→→→进入此内容的聊天室

来自 , 2020-08-27, 写在 C++, 查看 122 次.
URL http://www.code666.cn/view/8d8818c8
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int n;
  4. struct node
  5. {
  6.     int data;
  7.     int id;
  8.     struct node * left, *right;
  9. };
  10. struct node *creat(struct node *root, int x)
  11. {
  12.     if(!root)
  13.     {
  14.         struct node *t;
  15.         t= new node;
  16.         t->data = x;
  17.         t->left = t->right = NULL;
  18.         return t;
  19.     }
  20.     if(root->data < x)
  21.         root->left = creat(root->left, x);
  22.     else
  23.         root->right = creat(root->right, x);
  24.     return root;
  25.  
  26. };
  27. void bfs(struct node *root, int f)
  28. {
  29.     queue<node *>q;
  30.     root->id = 1;
  31.     q.push(root);
  32.     int flag = 0;
  33.     while(!q.empty())
  34.     {
  35.         if(flag)
  36.             cout<<" ";
  37.         struct node *now = q.front();
  38.         q.pop();
  39.         flag = 1;
  40.         if(now->id > n)
  41.             f = 1;
  42.         cout<<now->data;
  43.         if(now->left)
  44.         {
  45.             now->left->id = now->id<<1;
  46.             q.push(now->left);
  47.         }
  48.         if(now->right)
  49.         {
  50.             now->right->id = now->id<<1|1;
  51.             q.push(now->right);
  52.         }
  53.     }
  54.     cout<<endl;
  55.     if(f)
  56.         cout<<"NO";
  57.     else
  58.         cout<<"YES";
  59. }
  60. int main()
  61. {
  62.     struct node *root;
  63.     root = new node;
  64.     root = NULL;
  65.     int x, f = 0;
  66.     cin>>n;
  67.     for(int i = 0; i < n; i++)
  68.     {
  69.         cin>>x;
  70.         root = creat(root,x);
  71.     }
  72.     bfs(root,f);
  73.     return 0;
  74. }
  75.  

回复 "是否完全二叉搜索树"

这儿你可以回复上面这条便签

captcha