非常不熟练 照着书大的
晚上尝试一下自己打 了解二叉树 用数组打
第一次:
#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; }
原文地址:https://www.cnblogs.com/bxd123/p/10288458.html
时间: 2024-11-13 10:51:56