二叉树的遍历实例
合集下载
相关主题
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
btree creat_tree(btree,int);
void pre(btree);
void in(btree);
void post(btree);
int main(void)
{
int arr[]={1,2,34,4,46,46,6,46,4,4,5,6};
btree ptr=NULL;
cout<<"[原始数组内容]"<<endl;
#include<iostream>
#include<iomanip>
using namespace std;
class tree
{
public:
int data;
class tree *left,*right;
};
typedef class tree node;
typedef node *btree;
cout<<"中序遍历结果"<<endl;
in(ptr);
cout<<endl;
cout<<"后序遍历结果"<<endl;
post(ptr);
cout<<endl;
system("pause");
return 0;
}
btree creat_tree(btree root,int val)
{
btree newnode,current,backup;
for(int i=0;i<11;i++)
{ptr=creat_tree(ptr,arr[i]);
cout<<"["<<setw(2)<<arr[i]<<"]";
}
cout<<endl;
cout<<"[二叉树内容]"<<endl;
cout<<"前序遍历结果"<<endl;
pre(ptr);
cout<<endl;
newnode=new node;
newnode->data=val;
newnode->left=NULL;
newnode->right=NULL;
if(root==NULL)
{
root=newnode;
return root;
}
else
{
for(current=root;current!=NULL;)
}
return root;
}
void pre(btree ptr)
{
if(ptr !=NULL)
{
cout<<"["<<setw(2)<<ptr->data<<"]";
pre(ptr->left);
pre(ptr->right);
}
}
void in(btree ptr)
{
if(ptr!=NULL)
{Hale Waihona Puke Baidu
in(ptr->left);
cout<<"["<<setw(2)<<ptr->data<<"]";
in(ptr->right);
}
}
void post(btree ptr)
{
if(ptr!=NULL)
{
post(ptr->left);
post(ptr->right);
cout<<"["<<setw(2)<<ptr->data<<"]";
}
}
运行结果:
可根据实际情况改动!
{backup=current;
if(current->data>val)
current=current->left;
else
current=current->right;
}
if(backup->data>val)
backup->left=newnode;
else
backup->right=newnode;
void pre(btree);
void in(btree);
void post(btree);
int main(void)
{
int arr[]={1,2,34,4,46,46,6,46,4,4,5,6};
btree ptr=NULL;
cout<<"[原始数组内容]"<<endl;
#include<iostream>
#include<iomanip>
using namespace std;
class tree
{
public:
int data;
class tree *left,*right;
};
typedef class tree node;
typedef node *btree;
cout<<"中序遍历结果"<<endl;
in(ptr);
cout<<endl;
cout<<"后序遍历结果"<<endl;
post(ptr);
cout<<endl;
system("pause");
return 0;
}
btree creat_tree(btree root,int val)
{
btree newnode,current,backup;
for(int i=0;i<11;i++)
{ptr=creat_tree(ptr,arr[i]);
cout<<"["<<setw(2)<<arr[i]<<"]";
}
cout<<endl;
cout<<"[二叉树内容]"<<endl;
cout<<"前序遍历结果"<<endl;
pre(ptr);
cout<<endl;
newnode=new node;
newnode->data=val;
newnode->left=NULL;
newnode->right=NULL;
if(root==NULL)
{
root=newnode;
return root;
}
else
{
for(current=root;current!=NULL;)
}
return root;
}
void pre(btree ptr)
{
if(ptr !=NULL)
{
cout<<"["<<setw(2)<<ptr->data<<"]";
pre(ptr->left);
pre(ptr->right);
}
}
void in(btree ptr)
{
if(ptr!=NULL)
{Hale Waihona Puke Baidu
in(ptr->left);
cout<<"["<<setw(2)<<ptr->data<<"]";
in(ptr->right);
}
}
void post(btree ptr)
{
if(ptr!=NULL)
{
post(ptr->left);
post(ptr->right);
cout<<"["<<setw(2)<<ptr->data<<"]";
}
}
运行结果:
可根据实际情况改动!
{backup=current;
if(current->data>val)
current=current->left;
else
current=current->right;
}
if(backup->data>val)
backup->left=newnode;
else
backup->right=newnode;