您的位置:首页 > 编程语言 > C语言/C++

二叉树的递归遍历(思路简单清晰)

2017-12-14 11:31 288 查看
预先建立用数组表示的二叉树的内容,然后建立二叉树,并进行前序、中序、后序遍历的操作,代码如下:

#include<iostream>
#include<iomanip>
using namespace std;
class tree {
public:
int data;
class tree *left, *right;

};
typedef class tree* btree;
btree create_tree(btree,int);
void pre(btree);
void in(btree);
void post(btree);
int main()
{
int arr[] = {7,4,1,5,16,8,11,12,15,9,2};
btree ptr = nullptr;
cout << "[原始数组内容:]" << endl;
for (int i = 0; i < 11; i++)
{
ptr = create_tree(ptr,arr[i]);
cout << "[" << setw(2) << arr[i] << "]";
}
cout << endl;
cout << "二叉树内容" << endl;
cout << "前序遍历结果:" << endl;
pre(ptr);
cout << endl;
cout << "中序遍历结果:" << endl;
in(ptr);
cout << endl;
cout << "后序遍历结果:" << endl;
post(ptr);
system("pause");
return 0;
}
btree create_tree(btree root, int val)
{
btree newnode, current, backup=nullptr;
newnode = new tree;
newnode->data = val;
newnode->left = nullptr;
newnode->right = nullptr;
if (root == nullptr)
{
root = newnode;
return root;
}
else {
for (current = root; current != nullptr;)
{
backup = current;
if (current->data > val)
current = current->left;
else
current = current->right;
}
if (backup->data > val)
backup->left = newnode;
else backup->right = newnode;
}
return root;
}

void pre(btree ptr)//前序遍历
{
if (ptr != nullptr) {
cout << "[" << ptr->data << "]";
pre(ptr->left);
pre(ptr->right);
}
}
void in(btree ptr)//中序遍历
{
if (ptr != nullptr) {

in(ptr->left);
cout << "[" << ptr->data << "]" ;
in(ptr->right);
}
}
void post(btree ptr)//后序遍历
{
if (ptr != nullptr) {

post(ptr->left);

post(ptr->right);
cout << "[" << ptr->data << "]";
}
}
执行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息