微软面试题2 .

来源:互联网 发布:网络用语晕是什么意思 编辑:程序博客网 时间:2024/05/22 02:29

微软、谷歌、百度等公司经典面试100题[第1-60题] 

怎样从顶部开始逐层打印二叉树结点数据?请编程。

[cpp] view plaincopyprint?
  1. #include<iostream>   
  2. #include<queue>   
  3. #include<time.h>   
  4. using namespace std;  
  5. struct node  
  6. {  
  7.     int value;  
  8.     node* left;  
  9.     node* right;  
  10.     node(int v)  
  11.     {  
  12.         value = v;  
  13.         left = NULL;  
  14.         right = NULL;  
  15.     }  
  16. };  
  17. class bintree  
  18. {  
  19. private:  
  20.     node* root;  
  21. public:  
  22.     bintree()  
  23.     {  
  24.         root = NULL;  
  25.     }  
  26.     void insert(int value)  
  27.     {  
  28.         if(root == NULL)  
  29.             root = new node(value);  
  30.         else  
  31.         {  
  32.             node* tmp = root;  
  33.             node* parent = root;  
  34.             int flag = 0;  
  35.             while(tmp != NULL)  
  36.             {  
  37.                 parent = tmp;  
  38.                 srand(time(NULL));  
  39.                 flag = rand() % 2;  
  40.                 if(flag == 1)//奇数往左边走,偶数往右边走  
  41.                     tmp = tmp->left;  
  42.                 else tmp = tmp->right;  
  43.             }  
  44.             node* child = new node(value);  
  45.             if(flag == 1)  
  46.                 parent->left = child;  
  47.             else parent->right = child;  
  48.         }  
  49.     }  
  50.     void print()//逐层打印节点数据  
  51.     {  
  52.         if(root == NULL)  
  53.             return;  
  54.         queue<node*> q;  
  55.         node* tmp = root;  
  56.         q.push(tmp);  
  57.         int count = 0;  
  58.         int m = 0;  
  59.         while(!q.empty())//用队列存储节点  
  60.         {  
  61.             cout << (q.front())->value << ' ';  
  62.             node* parent = q.front();  
  63.             if(parent->left != NULL)  
  64.                 q.push(parent->left);  
  65.             if(parent->right != NULL)  
  66.                 q.push(parent->right);  
  67.             q.pop();  
  68.         }  
  69.     }  
  70. };  
  71.   
  72. int main()  
  73. {  
  74.     int i;  
  75.     bintree tree;  
  76.     while(true)  
  77.     {  
  78.         cin >> i;  
  79.         if(i == -1)  
  80.             break;  
  81.         tree.insert(i);  
  82.     }  
  83.     tree.print();  
  84.   
  85. }  
0 0
原创粉丝点击