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

非递归利用栈

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

猜你喜欢

转载自blog.csdn.net/qinxinli/article/details/81839837