C/C++:二叉树二叉链创建——前序中序后序遍历

/**
*
* Althor: Hacker Hao
* Create: 2023.11.1
*
*/
#include 
using namespace std;
#define ElemType int
#define MAXSIZE 200
typedef struct BiTNode
{
	ElemType data;
	struct BiTNode* lchild, * rchild;
}BTNode;

BTNode* Create(int val)
{
	BTNode* node = (BTNode*)malloc(sizeof(BTNode));
	node->data = val;
	node->rchild = NULL;
	node->lchild = NULL;
	return node;
}

void PreOrder(BTNode* root)
{
	BTNode* stack[MAXSIZE], * p;
	int top = 0;
	if (!root)
	{
		cout << "ERROR" << endl;
		exit(0);
	}

	stack[top] = root;
	while (top != -1)
	{
		p = stack[top];
		top--;

		cout << p->data << " ";
		if (p->rchild)
			stack[++top] = p->rchild;

		if (p->lchild)
			stack[++top] = p->lchild;
	}

}

void InOrder(BTNode *root) 
{
	BTNode* stack[MAXSIZE], * p, * q;
	if (!root) 
	{
		cout << "ERROR" << endl;
		exit(0);
	}
	int top = 0;
	p = root;

	while (top != 0 || p) 
	{
		if (p) {
			stack[++top] = p;
			p = p->lchild;
		}
		else 
		{
			p = stack[top];
			cout << p->data << " ";
			top--;
			p = p->rchild;
			

		}
	}
}

void PostOrder(BTNode* root) 
{
	BTNode *stack1[MAXSIZE], * stack2[MAXSIZE];
	if (!root) 
	{
		cout << "ERROR" << endl;
		exit(0);
	}
	int top1 = 0;
	int top2 = 0;

	stack1[++top1] = root;

	while (top1 != 0) {
		auto t = stack1[top1];
		top1--;
		stack2[++top2] = t;

		if (t->lchild) 
		{
			stack1[++top1] = t->lchild;
		}

		if (t->rchild) 
		{
			stack1[++top1] = t->rchild;
		}
	}

	while (top2 != 0) {
		auto t = stack2[top2];
		top2--;
		cout << t->data << " ";
	}
}
int main()
{
	cin.tie(0), cout.tie(0);
	BTNode* A = Create(1);
	BTNode* B = Create(2);
	BTNode* C = Create(3);
	BTNode* D = Create(4);
	BTNode* E = Create(5);
	BTNode* F = Create(6);
	BTNode* G = Create(7);
	BTNode* H = Create(8);

	A->lchild = B;
	A->rchild = C;
	B->lchild = D;
	B->rchild = E;
	E->lchild = G;
	E->rchild = H;
	C->rchild = F;

	cout << "前序遍历结果是:";
	PreOrder(A);
	cout << endl;

	cout << "中序遍历结果是:";
	InOrder(A);
	cout << endl;

	cout << "后序遍历结果是:";
	PostOrder(A);
	cout << endl;
    return 0;
}

你可能感兴趣的:(c++,c语言,算法)