【洛谷】P1305 新二叉樹
阿新 • • 發佈:2019-02-01
題目描述
輸入一串二叉樹,用遍歷前序打出。
輸入輸出格式
輸入格式:
第一行為二叉樹的節點數n。(n≤26)
後面n行,每一個字母為節點,後兩個字母分別為其左右兒子。
空節點用*表示
輸出格式:
前序排列的二叉樹
輸入輸出樣例
輸入樣例#1: 複製
6
abc
bdi
cj*
d**
i**
j**
輸出樣例#1: 複製
abdicj
看題解是根結點在第一行。如果不在第一行是會有一點點麻煩。
根結點在第一行的AC程式碼:
////CSDN部落格:https://blog.csdn.net/qq_40889820 #include<iostream> #include<sstream> #include<algorithm> #include<string> #include<cstring> #include<iomanip> #include<vector> #include<cmath> #include<ctime> #include<stack> #include<queue> #include<map> #define mem(a,b) memset(a,b,sizeof(a)) #define e 2.71828182 #define Pi 3.141592654 using namespace std; struct node { char ele; node* lc; node* rc; node(char c) { ele=c;lc=rc=NULL; } }; node* root=NULL; node* Find(char ch,node* n) { if(n==NULL) return NULL; if(n->ele==ch) return n; node* ans=Find(ch,n->lc);//先找左子樹 if(ans) return ans;//找到了就返回 else return Find(ch,n->rc); //左子樹沒找到在右子樹找 } void add_2node(string str) { char c=str[0],l=str[1],r=str[2]; node* pos=Find(c,root); node* lchild=new node(l); node* rchild=new node(r); pos->lc=lchild; pos->rc=rchild; return; } void preorder(node* n) { if(n->ele=='*'||n==NULL) return; cout<<n->ele; preorder(n->lc); preorder(n->rc); } int main() { int n; cin>>n; for(int i=1;i<=n;i++) { string str; cin>>str; if(i==1) root=new node(str[0]);//題目中根結點在第一行 add_2node(str); } preorder(root); }
根結點不在第一行(不知道A沒AC程式碼):
////CSDN部落格:https://blog.csdn.net/qq_40889820 #include<iostream> #include<sstream> #include<algorithm> #include<string> #include<cstring> #include<iomanip> #include<vector> #include<cmath> #include<ctime> #include<stack> #include<queue> #include<map> #define mem(a,b) memset(a,b,sizeof(a)) #define e 2.71828182 #define Pi 3.141592654 using namespace std; struct node { char ele; node* lc; node* rc; node(char c) { ele=c;lc=rc=NULL; } }; node* root=NULL; node* Find(char ch,node* n) { if(n==NULL) return NULL; if(n->ele==ch) return n; node* ans=Find(ch,n->lc);//先找左子樹 if(ans) return ans;//找到了就返回 else return Find(ch,n->rc); //左子樹沒找到在右子樹找 } void add_2node(string str) { char c=str[0],l=str[1],r=str[2]; node* pos=Find(c,root); if(pos!=NULL) { pos->lc=new node(l); pos->rc=new node(r); } //原先的根結點是新讀入結點的左子結點 else if((pos=Find(l,root))!=NULL) { node* ne=new node(c); ne->lc=root; ne->rc=new node(r); root=ne; } //原先的根結點是新讀入結點的右子結點 else { node* ne=new node(c); ne->rc=root; ne->lc=new node(l); root=ne; } return; } void preorder(node* n) { if(n->ele=='*'||n==NULL) return; cout<<n->ele; preorder(n->lc); preorder(n->rc); } int main() { int n; cin>>n; for(int i=1;i<=n;i++) { string str; cin>>str; if(i==1) root=new node(str[0]);//先假定在第一行 add_2node(str); } preorder(root); }