1. 程式人生 > >6-7 樹的層次遍歷 uva122

6-7 樹的層次遍歷 uva122

遍歷 lse bool splay node %s clas close 分享

非常不熟練 照著書大的

晚上嘗試一下自己打 了解二叉樹 用數組打

第一次:

技術分享圖片
#include<bits/stdc++.h>
using namespace std;
bool failed;


void addnode(int v,char *s);
char s[1000];
struct node
{
    bool  flag;
    int v;
     node *left,*right;
     node():flag(false),left(NULL),right(NULL){}

};
node *root;
node *newnode(){return
new node();} bool read_input() { failed=false; root=newnode(); for(;;) { if(scanf("%s",s)!=1)return false; if(!strcmp(s,"()")) break; int v; sscanf(&s[1],"%d",&v); addnode(v,strchr(s,,)+1); } return true; } void addnode(int
v,char *s) { int n=strlen(s); node *u=root; for(int i=0;i<n;i++) { if(s[i]==L) { if(u->left==NULL)u->left=newnode(); u=u->left; } else if(s[i]==R) { if(u->right==NULL)u->right=newnode(); u
=u->right; } } if(u->flag)failed=true; u->v=v; u->flag=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->flag)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() { vector<int>ans; while(read_input()) { if(!bfs(ans))failed=true; if(failed)printf("not complete\n"); else { for(int i=0;i<ans.size();i++) { if(i==ans.size()-1)printf("%d\n",ans[i]); else printf("%d ",ans[i]); } } } return 0; }
View Code

6-7 樹的層次遍歷 uva122