朋友的考試題,我是搞JAVA的c++和數據結構我都沒學過!以下都是經過解析copy && paste上去的,看得不太懂就那個意思拉~各位幫指點指點!如果能幫寫個正確的就更好了!
二叉樹的前序遍歷爲DBACFEG,中序遍歷爲ABCDEFG,那麼該二叉樹的後續遍歷的結果是什麼?請編程實現該二叉樹的三種遍歷。
答:後序遍歷的結果是 ACBEGFD。
#include<iostream.h>
struct tree
{
int data;
tree *left,*right;
};
class Btree
{
static int n;
static int m;
public:
tree *root;
Btree()
{
root=NULL;
}
void create_Btree(int);
void Preorder(tree *); //先序遍歷
void inorder(tree *); //中序遍歷
void Postorder(tree *); //後序遍歷
void display1() {Preorder(root); cout<<endl;}
void display2() {inorder(root);cout<<endl;}
void display3() {Postorder(root); cout<<endl;}
};
void Btree::create_Btree(int x)
{
tree *newnode=new tree;
newnode->data=x;
newnode->right=newnode->left=NULL;
if(root==NULL)
root=newnode;
else
{
tree *back;
tree *current=root;
while(current!=NULL)
{
back=current;
if(current->data>x)
current=current->left;
else
current=current->right;
}
if(back->data>x)
back->left=newnode;
else
back->right=newnode;
}
}
void Btree::Preorder(tree *temp) //這是先序遍歷二叉樹,採用了遞歸的方法。
{
if(temp!=NULL)
{
cout<<temp->data<<" ";
Preorder(temp->left);
Preorder(temp->right);
}
}
void Btree::inorder(tree *temp) //這是中序遍歷二叉樹,採用了遞歸的方法。
{
if(temp!=NULL)
{
inorder(temp->left);
cout<<temp->data<<" ";
inorder(temp->right);
}
}
void Btree::Postorder(tree *temp) //這是後序遍歷二叉樹,採用了遞歸的方法。
{
if(temp!=NULL)
{
Postorder(temp->left);
Postorder(temp->right);
cout<<temp->data<<" ";
}
}
void main()
{
Btree A;
int array[]={'D','B','A','C','F','E','G'};
int k;
k=sizeof(array)/sizeof(array[0]);
cout<<"建立排序二叉樹順序: "<<endl;
for(int i=0;i<k;i++)
{
cout<<array[i]<<" ";
A.create_Btree(array[i]);
}
cout<<endl;
cout<<endl<<"先序遍歷序列: "<<endl;
A. display1();
cout<<endl<<"中序遍歷序列: "<<endl;
A.display2();
cout<<endl<<"後序遍歷序列: "<<endl;
A.display3();
}
2.二叉樹的查找(編程實現)
依次輸入下面元素
55,78,34,43,80,34,36,90,84,78
試構造一棵二叉樹,並在樹中查找60。如果有請輸出存儲號,若果沒有請輸出“無此數”。
(這道題我正在研究中)
二叉樹
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.