二叉树的遍历算法

二叉树的遍历算法分为三种,根据对父节点的遍历顺序分为先序遍历、中序遍历以及后序遍历。其中可使用递归方式以及非递归方式,递归方式程序非常简单,但是效率相对较低,在非递归i方式中,借助栈来对数据进行存储。

定义树中节点的数据结构如下所示:

typedef struct _node {
       struct _node *left_child;
       struct _node *right_child;
       ctype_t    data;
}node, *tree; //二叉树节点结构
二叉树的递归遍历和非递归遍历算法如下所示:

void preorder_recursion(tree root)
{
	if (NULL != root)
	{
		printf("%d/t", root->data);            //根
		preorder_recursion(root->left_child);    //左子树
		preorder_recursion(root->right_child);  //右子树
	}
}

void preorder_nonrecursive(tree root)
{
	tree stack[100];
	int top = 0;
	tree p=root;
	while (NULL != p || top > 0)
	{
		while (NULL != p)
		{
			printf("%d/t", p->data);
			stack[top++] = p;
			p=p->left_child;
		}
		p = stack[--top];
		p = p->right_child;
	}
}

void inorder_recursion(tree root)
{
	if (NULL != root)
	{
		inorder_recursion(root->left_child);             //左子树
		printf("%d/t", root->data);            //根
		inorder_recursion(root->right_child);    //右子树
	}
}

void inorder_nonrecursive(tree root)
{
	tree stack[100];
	int top = 0;
	tree p = root;
	while (NULL != p || top > 0)
	{
		while (NULL != p)
		{
			stack[top++] = p;
			p = p->left_child;
		}

		p = stack[--top];
		printf("%d/t", p->data);
		p = p->right_child;
	}
}

void postorder_recursion(tree root)
{
	if (NULL != root)
	{
		postorder_recursion(root->left_child);
		postorder_recursion(root->right_child);
		printf("%d/t", root->data);
	}
}

void postorder_nonrecursive(tree root)
{
	tree stack[100];
	int top=0;
	tree p = root;
	tree lastvist = NULL;
	while (NULL != p || top > 0)
	{
		while (NULL != p)
		{
			stack[top++] = p;
			p = p->left_child;
		}

		p = stack[top-1];
		if (NULL == p->right_child || lastvist == p->right_child)
		{
			printf("%d/t", p->data);
			--top;
			lastvist = p;
			p = NULL;
		}
		else
		{
			p = p->right_child;
		}
	}
}







  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值