微软面试题2 .
来源:互联网 发布:网络用语晕是什么意思 编辑:程序博客网 时间:2024/05/22 02:29
微软、谷歌、百度等公司经典面试100题[第1-60题]
怎样从顶部开始逐层打印二叉树结点数据?请编程。
- #include<iostream>
- #include<queue>
- #include<time.h>
- using namespace std;
- struct node
- {
- int value;
- node* left;
- node* right;
- node(int v)
- {
- value = v;
- left = NULL;
- right = NULL;
- }
- };
- class bintree
- {
- private:
- node* root;
- public:
- bintree()
- {
- root = NULL;
- }
- void insert(int value)
- {
- if(root == NULL)
- root = new node(value);
- else
- {
- node* tmp = root;
- node* parent = root;
- int flag = 0;
- while(tmp != NULL)
- {
- parent = tmp;
- srand(time(NULL));
- flag = rand() % 2;
- if(flag == 1)//奇数往左边走,偶数往右边走
- tmp = tmp->left;
- else tmp = tmp->right;
- }
- node* child = new node(value);
- if(flag == 1)
- parent->left = child;
- else parent->right = child;
- }
- }
- void print()//逐层打印节点数据
- {
- if(root == NULL)
- return;
- queue<node*> q;
- node* tmp = root;
- q.push(tmp);
- int count = 0;
- int m = 0;
- while(!q.empty())//用队列存储节点
- {
- cout << (q.front())->value << ' ';
- node* parent = q.front();
- if(parent->left != NULL)
- q.push(parent->left);
- if(parent->right != NULL)
- q.push(parent->right);
- q.pop();
- }
- }
- };
- int main()
- {
- int i;
- bintree tree;
- while(true)
- {
- cin >> i;
- if(i == -1)
- break;
- tree.insert(i);
- }
- tree.print();
- }
0 0
- 微软面试题 2
- 微软面试题【2】
- 微软面试题2
- 微软面试题2 .
- 微软面试题 07012012[2]
- 微软面试题 07022012 [2]
- 微软面试题[1-2]
- 微软面试-微软面试题(2)
- 微软面试题汇总(2)
- 微软面试题汇总(2)
- 微软的面试题(答案)(2)
- 微软面试题程序(2)
- c++练习2 微软面试题
- 一道微软面试题
- 微软面试题
- 微软面试题
- 微软面试题(转载)
- 微软面试题
- nyoj263精挑细选
- Python 深入理解yield
- 关键路径法
- 软件测试的起点和源泉——七种测试驱动模式(方法论) .
- SPOJ 11840. Sum of Squares with Segment Tree (线段树,区间更新)
- 微软面试题2 .
- 李林APUE之进程的封装
- Git使用基础 .
- [ACM] HUST 1017 Exact cover (Dancing Links,DLX模板题)
- 好友列表
- Git(一):Git与版本控制简介 .
- Redhat linux下安装oracle11r2手册+截图_toto_V1.0
- OpenGL在 Visual Studio 2008/2010 和 VC6++ 上面的配置(学习笔记)
- Ural 1119 Metro(DP)