标签:linux c++
创建先序二叉树
#include<iostream> using namespace std; class BinTreeNode { public: char ch; BinTreeNode(int value){ch=value;} BinTreeNode *left,*right; }; BinTreeNode* create_tree() { char item; BinTreeNode *t,*t_l,*t_r; cin>>item; if(item!=‘#‘) { BinTreeNode *pTmpNode=new BinTreeNode(item); t=pTmpNode; t_l=create_tree(); t->left=t_l; t_r=create_tree(); t->right=(t_r); return t; } else { t=NULL; return t; } } void midsearch(BinTreeNode *root) { if(root!=NULL) cout<<(root->ch); else return ; midsearch(root->left); midsearch(root->right); } void leftsearch(BinTreeNode *root) { if(root==NULL) return ; leftsearch(root->left); cout<<(root->ch); leftsearch(root->right); } void rightsearch(BinTreeNode *root) { if(root==NULL) return ; rightsearch(root->left); rightsearch(root->right); cout<<(root->ch); } int main() { BinTreeNode *root=create_tree(); midsearch(root); //先序遍历 cout<<endl; leftsearch(root); //中序遍历 cout<<endl; rightsearch(root); //后序遍历 cout<<endl; return 0; }
创建层次遍历树
#include<iostream> #include<queue> using namespace std; class BinTreeNode { public: char ch; BinTreeNode(char value){ch=value;} BinTreeNode *left,*right; char get_data(); BinTreeNode* get_left(); BinTreeNode* get_right(); }; char BinTreeNode::get_data() { return ch; } BinTreeNode* BinTreeNode::get_left() { return left; } BinTreeNode* BinTreeNode::get_right() { return right; } BinTreeNode* level_create() { char data,data1,data2; BinTreeNode* r; cin>>data; if(data==‘#‘) return r; r=new BinTreeNode(data); deque<BinTreeNode*> q; q.push_back(r); while(!q.empty()) { BinTreeNode *p=q.front(); q.pop_front(); cin>>data1; if(data1!=‘#‘) { p->left=new BinTreeNode(data1); q.push_back(p->left); } cin>>data2; if(data2!=‘#‘) { p->right=new BinTreeNode(data2); q.push_back(p->right); } } return r; } void midsearch(BinTreeNode *root) { if(root!=NULL) cout<<(root->ch); else return ; midsearch(root->left); midsearch(root->right); } void leftsearch(BinTreeNode *root) { if(root==NULL) return ; leftsearch(root->left); cout<<(root->ch); leftsearch(root->right); } void rightsearch(BinTreeNode *root) { if(root==NULL) return ; rightsearch(root->left); rightsearch(root->right); cout<<(root->ch); } void level_order(BinTreeNode *r) { if(r==NULL) return ; deque<BinTreeNode*> q; q.push_back(r); while(!q.empty()) { BinTreeNode *p=q.front(); cout<<p->get_data()<<" "; q.pop_front(); if(p->get_left()!=NULL) { q.push_back(p->get_left()); } if(p->get_right()!=NULL) { q.push_back(p->get_right()); } } } int main() { BinTreeNode *root=level_create(); midsearch(root); //先序遍历 cout<<endl; leftsearch(root); //中序遍历 cout<<endl; rightsearch(root); //后序遍历 cout<<endl; level_order(root); //层次遍历 cout<<endl; return 0; }
以上两个程序都是根据已有的遍历结果来创建对应的树
标签:linux c++
原文地址:http://yuzwei.blog.51cto.com/10126623/1671045