Bloomberg 面试题05012012[2]

来源:互联网 发布:linux 编译内核作用 编辑:程序博客网 时间:2024/06/06 04:11

You have a binary tree. Print node values starting from the root going level by level, i.e. first line has root node's value, second line has two child node's values, third line - left and right child nodes values of the root's left child then left and right child nodes values of the root's right child, and so on.


#include <iostream>#include <queue>struct node{int data;node* left;node* right;node(int _data, node* _left, node* _right){data = _data;left = _left;right = _right;}};int main(){node* n7 = new node(7, NULL, NULL);node* n6 = new node(6, NULL, NULL);node* n5 = new node(5, NULL, NULL);node* n4 = new node(4, NULL, NULL);node* n3 = new node(3, n6, n7);node* n2 = new node(2, n4, n5);node* n1 = new node(1, n2, n3);node* root = n1;std::queue<node*> q;q.push(root);q.push(NULL);while(!q.empty()){node* cur = q.front();if(cur != NULL){printf("%d ", cur->data);q.pop();if(cur->left != NULL)q.push(cur->left);if(cur->right != NULL)q.push(cur->right);}else{if(q.size() == 1)break;else{q.pop();q.push(NULL);printf("\n");}}}return 0;}


原创粉丝点击