二叉树先中后序遍历(递归与非递归)

非递归利用栈

#include <iostream>
#include <stack>

using namespace std;

typedef struct BinaryTree {
	char data;
	BinaryTree* lchild;
	BinaryTree* rchild;
}BinaryTree;

typedef struct MYDATA {
	BinaryTree* binarytree;
	int flag;
}MyData;

void NonRecursion(BinaryTree* btree) {
	stack<MyData> s;
	MyData mydata, temp,temp1;
	mydata.binarytree = btree;
	mydata.flag = 0;
	s.push(mydata);
	while (s.size() > 0) {
		temp = s.top();
		s.pop();
		if (temp.flag == 1) {
			cout << temp.binarytree->data;
		}
		else {
			// 右孩子
			if (temp.binarytree->rchild != NULL) {
				temp1.binarytree = temp.binarytree->rchild;
				temp1.flag = 0;
				s.push(temp1);
			}
			//  根节点
			temp.flag = 1;
			s.push(temp);
		    // 左孩子
			if (temp.binarytree->lchild != NULL) {
				temp1.binarytree = temp.binarytree->lchild;
				temp1.flag = 0;
				s.push(temp1);
			}
		}
	}
}

void CreateBinaryTree()
{
	BinaryTree node1 = { 'A', NULL, NULL };
	BinaryTree node2 = { 'B', NULL, NULL };
	BinaryTree node3 = { 'C', NULL, NULL };
	BinaryTree node4 = { 'D', NULL, NULL };
	BinaryTree node5 = { 'E', NULL, NULL };
	BinaryTree node6 = { 'F', NULL, NULL };
	BinaryTree node7 = { 'G', NULL, NULL };
	BinaryTree node8 = { 'H', NULL, NULL };

	node1.lchild = &node2;
	node1.rchild = &node6;
	node2.rchild = &node3;
	node3.lchild = &node4;
	node3.rchild = &node5;
	node6.rchild = &node7;
	node7.lchild = &node8;

	NonRecursion(&node1);
	cout << endl;
}

int main()
{
	CreateBinaryTree();
	system("pause");
	return 0;
}

递归遍历:

#include <iostream>

using namespace std;

typedef struct BinaryTree {
	char data;
	BinaryTree* lchild;
	BinaryTree* rchild;
}BinaryTree;


// 二叉树的递归遍历
void Recursion(BinaryTree* node) {
	if (node == NULL)
		return;
	
	Recursion(node->lchild);
	
	Recursion(node->rchild);

	cout << node->data;
}

void CreateBinaryTree()
{
	BinaryTree node1 = { 'A', NULL, NULL };
	BinaryTree node2 = { 'B', NULL, NULL };
	BinaryTree node3 = { 'C', NULL, NULL };
	BinaryTree node4 = { 'D', NULL, NULL };
	BinaryTree node5 = { 'E', NULL, NULL };
	BinaryTree node6 = { 'F', NULL, NULL };
	BinaryTree node7 = { 'G', NULL, NULL };
	BinaryTree node8 = { 'H', NULL, NULL };

	node1.lchild = &node2;
	node1.rchild = &node6;
	node2.rchild = &node3;
	node3.lchild = &node4;
	node3.rchild = &node5;
	node6.rchild = &node7;
	node7.lchild = &node8;


	// 先序遍历
	Recursion(&node1);
	cout << endl;

	BinaryTree* newnode = CopyBinaryTree(&node1);
	Recursion(newnode);
	cout << endl;
	FreeBinaryTree(newnode);
}

int main()
{
	CreateBinaryTree();
	system("pause");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值