输入一颗二元树,从上往下按层打印树的每个结点,同一层中按照从左往右的顺序打印。
例如输入
8
/ /
6 10
/ /
/ /
5 7 9 11
输出8 6 10 5 7 9 11。
- #include <iostream>
- struct Node
- {
- int data_;
- Node* left;
- Node* right;
- Node(int d = 0,Node* lr = 0,Node* rr = 0):data_(d),left(lr),right(rr) {}
- };
- void bfs(Node* root)
- {
- const int MAXN = 256;
- Node* q[MAXN];
- int front = 0, rear = 0;
- q[rear++] = root;
- while (front < rear)
- {
- Node*& value = q[front++];
- if (value->left) q[rear++] = value->left;
- if (value->right) q[rear++] = value->right;
- }
- front = 0;
- while (front < rear)
- {
- printf("%d,",q[front++]->data_);
- }
- }
- int main()
- {
- Node *root = new Node(8);
- root->left = new Node(6);
- root->right = new Node(10);
- root->left->left = new Node(5);
- root->left->right = new Node(7);
- root->right->left = new Node(9);
- root->right->right = new Node(11);
- bfs(root);
- }
阅读(556) | 评论(0) | 转发(1) |