二叉树--uva122 二叉树层次遍历(结构体+指针解法)

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

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

/*
@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;
}


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值