二叉樹建立,遍歷(類)
阿新 • • 發佈:2018-12-28
程式碼:
#include<iostream> #include<queue> using namespace std; //建立節點 struct Tnode { char data;//資料域 Tnode *rchild;//右孩子 Tnode *lchild;//左孩子 }; //定義類 class Tree { public: Tree(){root=CreatTree(root);} ~Tree(){} Tnode *CreatTree(Tnode *&T); void PreOder(Tnode *T); void InOder(Tnode *T); void PosOder(Tnode *T); void LeverOder(Tnode *T); Tnode *root; }; //建立二叉樹 Tnode* Tree::CreatTree(Tnode *&T)//遞迴建樹 { char a; cin>>a; if(a=='#') T=NULL; else { T=new Tnode;//對比之前new後加() T->data=a; T->lchild=CreatTree(T->lchild);//生成左子樹 T->rchild=CreatTree(T->rchild);//生成右子樹 } return T; } //前序遍歷 void Tree::PreOder(Tnode *root) { if(root) { cout<<root->data<<" ";//輸出父親節點 PreOder(root->lchild);//輸出左子樹 PreOder(root->rchild);//輸出右子樹 } } //中序遍歷 void Tree::InOder(Tnode *root) { if(root) { InOder(root->lchild); cout<<root->data<<" "; InOder(root->rchild); } } //後序遍歷 void Tree::PosOder(Tnode *root) { if(root) { PosOder(root->lchild); PosOder(root->rchild); cout<<root->data<<" "; } } //層序遍歷 //採用佇列輸出一節點的同時將其左右孩子入隊,重複操作直至佇列為空 void Tree::LeverOder(Tnode *root) { if(root) { queue<Tnode*> Q; Q.push(root); while(!Q.empty()) { Tnode *q=Q.front(); Q.pop(); cout<<q->data<<" "; if(q->lchild!=NULL) Q.push(q->lchild); if(q->rchild!=NULL) Q.push(q->rchild); } } } //main函式 int main() { Tree A; cout<<endl<<"前序遍歷:"; A.PreOder(A.root); cout<<endl<<"中序遍歷:"; A.InOder(A.root); cout<<endl<<"後序遍歷:"; A.PosOder(A.root); cout<<endl<<"層序遍歷:"; A.LeverOder(A.root); return 0; }
截圖: