本文主要是介绍关于二叉树的非递归遍历的算法疑惑,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
二叉树的遍历让递归算法的思想得到了无限的魅力施展,可以说二叉树的操作由于递归而变得简单和易于操作,只要搞清楚递归的本质和代码原理即可
但是要想脱离递归而遍历二叉树的所有元素,真的有点困难。
网上最多的一个算法是应用栈的入栈和出栈。
我看了一些帖子,有点看不懂,自己尝试用流程框架来打印出所有元素,但都失败了,要么只能打印特定的二叉树,要么是重复打印,所以在想是不是除了栈,没有其他的方法了
附上我的代码:
期待高手指点迷津:
//中序遍历--左中右打印
int print_middle(pnode_t proot)
{
if(proot == NULL)
{
printf("print wrong\n");
return;
}
pnode_t father = NULL;
pnode_t tmp = NULL;
tmp = father;
while(proot != NULL)
{
//printf("here2\n");
father = proot;
if((father->data == 9)&&( father->left == NULL)&&(father->right == NULL))
{
break;
}
while(father != NULL)
{
//printf("here2\n");
//printf("data=%d\n",proot->data);
//break;
//father = proot;
while( father != NULL )
{
tmp = father;
father = father->left;
}
father = tmp;
printf("%d ",father->data);
if(father->right != NULL)
{
father = father->right;
}
tmp = father;
//printf("%d\n",father->data);
//break;
//printf("here\n");
if((father->left == NULL)&&(father->right == NULL))
{
//printf("here2\n");
pnode_t new = NULL;
new = find_lr_node(proot,father->data);
//printf("new=%d\n",new->data);
//printf("father=%d\n",father->data);
if(new->left != NULL)
{
if(new->left->data == father->data)
{
printf("%d ",new->data);
new->left = NULL;
father = NULL;
pnode_t p = NULL;
p = find_lr_node(proot,new->data);
//printf("p=%d\n",p->data);
if(p->left != NULL)
{
if(p->left->data == new->data)
p->left = NULL;
new = NULL;
}
else if(p->right != NULL)
{
//printf("here3\n");
if(p->right->data == new->data)
//free(p->right);
p->right = NULL;
new = NULL;
}
//free(p->right);
//printf("p=%d\n",p->data);
//break;
}
}
else if(new->right != NULL)
{
if(new->right->data == father->data)
{
printf("%d ",new->data);
new->right = NULL;
father = NULL;
pnode_t pp = NULL;
pp = find_lr_node(proot,new->data);
if(pp->left != NULL)
{
if(pp->left->data == new->data)
pp->left = NULL;
new = NULL;
}
if(pp->right != NULL)
{
if(pp->right->data == new->data)
pp->right = NULL;
new = NULL;
}
}
}
//printf("here5\n");
//printf("here\n");
//break;
}
//printf("here6\n");
}
}
printf("\n");
}
这篇关于关于二叉树的非递归遍历的算法疑惑的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!