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

预先建立用数组表示的二叉树的内容,然后建立二叉树,并进行前序、中序、后序遍历的操作,代码如下:

#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 << "]";
	}
}
执行结果:



  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值