标签:
在确定只有N个元素的时候,使用bfs建立二叉树的方法。
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
#define N 10000
struct Node
{
Node* l;
Node* r;
int data;
};
Node* NewNode() {
Node* n = (Node*)malloc(sizeof(Node));
if (n) {
n->l = NULL;
n->r = NULL;
n->data = -1;
}
return n;
}
Node* create()
{
queue<Node*> q;
Node* root = NewNode();
q.push(root);
int lmt = 1;
while (!q.empty())
{
Node* p = q.front();
cin >> p->data;
q.pop();
if (lmt + 2 <= N) {
Node* l = NewNode();
Node* r = NewNode();
p->l = l;
p->r = r;
q.push(l);
q.push(r);
lmt += 2;
} else if (lmt + 1 == N) {
Node* l = NewNode();
p->l = l;
q.push(l);
lmt += 1;
} else if (lmt == N) {
break;
}
}
while (!q.empty()) {
cin >> q.front()->data;
q.pop();
}
return root;
}
void bfs(Node* root) {
queue<Node*> q;
q.push(root);
int lmt = 1;
while (!q.empty()) {
if (lmt > N) break;
Node* p = q.front();
cout << p->data << " ";
lmt++;
q.pop();
if (p->l) q.push(p->l);
if (p->r) q.push(p->r);
}
cout << endl;
}
void dfs(Node* n) {
if (!n) return ;
cout << n->data << " ";
dfs(n->l);
dfs(n->r);
}
int main() {
Node* root = create();
bfs(root);
dfs(root);
return 0;
}
标签:
原文地址:http://www.cnblogs.com/marginalman/p/4822116.html