朋友的考试题,我是搞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。如果有请输出存储号,若果没有请输出“无此数”。
(这道题我正在研究中)
二叉树
最新推荐文章于 2024-06-10 11:43:53 发布