二叉树的前序遍历,中序遍历,后序遍历(非递归方法+C语言代码)

#include<stdlib.h>
#include<stdio.h>
#include<assert.h>
#include<stdbool.h>
//定义一个二叉树结点结构体
typedef int ElemTpye;
typedef struct TreeNode
{
	ElemTpye data;
	struct TreeNode* left;
	struct TreeNode* right;
}TreeNode;
//创建结点
TreeNode* createTreenode(ElemTpye data)
{
	TreeNode* newnode = (TreeNode*)malloc(sizeof(TreeNode));
	assert(newnode);
	newnode->data = data;
	newnode->left = NULL;
	newnode->right = NULL;
	return newnode;
}
//非递归的前序遍历
void preOrderTraversal(TreeNode* root)
{
	if (root == NULL)
	{
		return;
	}
	//设置一个栈
	TreeNode* Stack[100];
	int top = -1;
	Stack[++top] = root;
	while (top >= 0)
	{
		TreeNode* current = Stack[top--];
		printf("%d ", current->data);

		if (current->right!=NULL)
		{
			Stack[++top] = current->right;
		}
		if (current->left!=NULL)
		{
			Stack[++top] = current->left;
		}
	}
}
//非递归的中序遍历
void inOrderTraversal(TreeNode* root)
{
	if (root == NULL)
	{
		return;
	}
	//设置一个栈
	TreeNode* Stack[100];
	int top = -1;
	TreeNode* current = root;
	while (current!=NULL || top>=0)
	{
		while (current != NULL)
		{
			Stack[++top] = current;
			current = current->left;
		}
		current = Stack[top--];
		printf("%d ", current->data);
		current = current->right;
	}
}
//非递归的后序遍历
void postOrderTraversal(TreeNode* root)
{
	if (root == NULL)
	{
		return;
	}
	//设置两个栈
	TreeNode* Stack1[100],* Stacck2[100];
	int top1 = -1, top2 = -1;
	Stack1[++top1] = root;
	while (top1>=0)
	{
		TreeNode* current = Stack1[top1--];
		Stacck2[++top2] = current;

		if (current->left != NULL)
		{
			Stack1[++top1] = current->left;
		}
		if (current->right != NULL)
		{
			Stack1[++top1] = current->right;
		}
	}
	while (top2>=0)
	{
		TreeNode* current = Stacck2[top2--];
		printf("%d ", current->data);
	}
}
// 释放二叉树内存
void freeTree(struct TreeNode* root) {
	if (root == NULL)
		return;
	freeTree(root->left);
	freeTree(root->right);
	free(root);
}
int main()
{
	TreeNode* root = NULL;
	root = createTreenode(1);
	root->left = createTreenode(2);
	root->right = createTreenode(3);
	root->left->left = createTreenode(4);
	root->left->right = createTreenode(5);
	root->right->left = createTreenode(6);
	root->right->right = createTreenode(7);

	printf("非递归前序遍历如下\n");
	preOrderTraversal(root);
	printf("\n");

	printf("非递归中序遍历如下\n");
	inOrderTraversal(root);
	printf("\n");

	printf("非递归后序遍历如下\n");
	postOrderTraversal(root);
	printf("\n");

	freeTree(root);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值