二叉树--uva122 结构体+指针解法

来源:互联网 发布:电脑桌面工作提醒软件 编辑:程序博客网 时间:2024/06/07 04:44

题意:输入一个二叉树,让你按照从上到下,从左到右的顺序输出这颗二叉树。

分析:哈哈哈,终于自己不看书实现了一次,激动人心啊!

/*@Filename:        test.cpp@Author:        wyl6 @Mail:            ustbcs_wyl@163.com@Thought:*/#include <cstdio>#include <cstdlib>#include <iostream>#include <stack>#include <queue>#include <algorithm>#include <cstring>#include <string>#include <cmath>#include <vector>#include <bitset>#include <list>#include <sstream>#include <set>#include <functional>using namespace std;const int MAX = 100;char s[MAX];bool faild;struct node{    int v;    node * left,*right;    bool have_Value;    node():v(0),left(NULL),right(NULL),have_Value(false){}};node *root;node *NewNode(){    return new node();}void Del_Tree(node *u){    if(u == NULL) return;    Del_Tree(u->left);    Del_Tree(u->right);    delete u;}void AddNode(int v,char *s)//字符数组传入字符指针变量{    int len = strlen(s);    node *t = root;    for (int i = 0; i < len; ++i){        if (s[i] == 'L'){            if(t->left == NULL) t->left = NewNode();            t = t->left;        }else if (s[i] == 'R'){            if(t->right == NULL) t->right = NewNode();            t = t->right;        }    }    if(t->have_Value) faild = true;    t->v = v;    t->have_Value = true;}bool Input_Tree(){    root = NewNode();    faild = false;    for (;;){        if(scanf("%s",s) != 1) return false;        if(!strcmp(s,"()")) break; //相同返回0,不同返回1        int v;        sscanf(&s[1],"%d",&v);  //sscanf(a,b,c),从a中读取b格式的数据,存入c中        AddNode(v,strchr(s,',')+1);//strchr(str,c)从str中找到c的第一个位置    }    return true;}bool Bfs(vector<int >&ans){    queue<node*> q;    ans.clear();    q.push(root);    while(!q.empty()) {        node *u = q.front();q.pop();        if(!u->have_Value) return false;        ans.push_back(u->v);        if(u->left != NULL) q.push(u->left);        if(u->right != NULL) q.push(u->right);    }     return true;}int main(){    while(1) {        Del_Tree(root);        if(!Input_Tree()) break;        vector<int> ans;        if(!faild && Bfs(ans)){            int len = ans.size();            for (int i = 0; i < len; ++i)                cout << ans[i] << (i == (len-1)?'\n':' ');        }else cout << "not complete" << endl;    }    return 0;}


参考:刘大爷的紫书第六章

原创粉丝点击