递归法(非递归法)遍历二叉树
来源:互联网 发布:java int super 编辑:程序博客网 时间:2024/05/04 05:02
- 2.4 用递归法(非递归法)实现先序遍历、中序遍历和后序遍历函数,要求遍历时能执行一定的操作,且该操作可由遍历函数的调用者来设置。
提示:可将结点定义成如下结构体:
#define TREE_TYPE int
typedef struct TREE_NODE{
TREE_TYPE value;
struct TREE_NODE *left; 左结点指针
struct TREE_NODE *right; 右结点指针
}TreeNode;
先序遍历与创建二叉树;递归法
#include "tree.h"
#include <stdio.h>
btree *creat_bintree(btree *t)
{ char ch;
printf("/n enter ch in preorder, 1 for no child:");
ch=getchar();
getchar();
if ( ch=='1')
{
printf("The tree has only head node!/n");
t = NULL;
}
else
{
t = (btree *)malloc(sizeof(btree));
t->data=ch;
t->lchild = (btree *)creat_bintree( t->lchild );
t->rchild = (btree *)creat_bintree( t->rchild );
}
return(t);
}
非递归实现;
#include "tree.h"
void preorder_norecu(btree *t)
{
btree *s[20], *p =t; //p is the current node
int top = 0;
while(p || top) // p isn't NULL
if(p)
{
visit(p); //visit the cur node
++top;
s[top] = p; //save cur node to s[top];
p=p->lchild; //p is directed to lchild node;
}
else //p is NULL
{
p=s[top]; //let p direct to s[top];
--top; //decrease the top;
p=p->rchild; //test rchild is NULL or not?
}
}
中序遍历;
#include "tree.h"
void in_tree(btree *t)
{
if(t == NULL)
return -1;
else
{
in_tree(t->lchild);
putchar(t->data);
in_tree(t->rchild);
}
}
非递归实现:
#include "tree.h"
void in_norecursive(btree *t)
{
btree * s[MAX],*p=t; //p is directed to head node;
int top=0;
while(p || top !== NULL) //p isn't NULL
if(p)
{
top++; //top add
s[top]=p; //save current node;
p=p->lchild; //let p directed to lchild;
}
else
{
p=s[top]; //p is NULL,let p directed to s[top];
--top; //push(s)
visit(p); //visit the p node;
p=p->rchild; //direct the right child;
}
}
后续遍历同上;
- 递归法(非递归法)遍历二叉树
- 二叉树递归非递归遍历(递归前中后,非递归前中后,层次遍历,凹入打印法等)
- 二叉树遍历(递归,非递归)
- 【数据结构】递归与非递归法遍历二叉树
- 二叉树遍历(递归、非递归、Morris遍历)
- 二叉树遍历(递归、非递归、Morris遍历)
- 二叉树的遍历(递归+非递归+层次遍历)
- 二叉树(4)非递归法遍历二叉树
- Lintcode 二叉树的前序遍历 (递归和非递归法)
- 二叉树建立、递归、非递归遍历
- JAVA递归、非递归遍历二叉树
- 非递归、递归遍历二叉树!
- 二叉树的递归,非递归遍历
- 递归 和 非递归 遍历二叉树
- 二叉树 递归 与 非递归 遍历
- 二叉树递归,非递归,前中后遍历
- 二叉树递归/非递归遍历
- 二叉树的递归+非递归遍历
- 【转】C++箴言:理解inline化的介入和排除
- Address already in usr
- 链表操作:创建,插入,删除,查找等功能
- 二分查找算法
- 有序二叉树的操作
- 递归法(非递归法)遍历二叉树
- 本人(初学者)在写小程序时经常犯的语法错误,在此总结一下
- 基于MIPS的uBoot编译环境搭建
- 八个硬币
- C++中string的学习
- Android系统介绍与移植
- 梅花雪
- Android地址
- 什么是程序设计第二小组答案