码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的bfs建立

时间:2015-09-19 21:11:40      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

在确定只有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;
}

  

二叉树的bfs建立

标签:

原文地址:http://www.cnblogs.com/marginalman/p/4822116.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!