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

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

#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 << "]";
	}
}

执行结果:

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

    原文作者:LA_James
    原文地址: https://blog.csdn.net/u012677715/article/details/78800829
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞