中序遍历非递归算法(C语言版)
2015-11-30 21:39
537 查看
#include <stdio.h>
#include <stdlib.h>
#define M 100
//前序遍历:ABD#E##FG###C##
typedef struct tree/*二叉树*/
{ char data;
struct tree *lchild,*rchild;
}bintree;
typedef bintree *tree;
tree createTree()/*前序遍历建树*/
{
tree t;
char c=getchar();
if(c=='#') return NULL;
else
{ t=(tree)malloc(sizeof(bintree));
t->data=c;
t->lchild=createTree();
t->rchild=createTree();
}
return t;
}
/*非递归中序遍历:思路:边遍历边输出,先输出左子树的最左边一个节点,并放入栈,*/
void intree(tree t)
{ tree stack[M];int top=0;/*定义、初始化栈*/
while(top||t)
{ if(t!=NULL)
{ stack[top++]=t;
t=t->lchild;
}else if(top!=0)
{ t=stack[--top];
printf("%c",t->data);
t=t->rchild;
}
}
}
/*中序遍历求首点*/
tree findFir(tree t)
{
if(t==NULL) return t;
tree p=t;
while(p->lchild!=NULL) p=p->lchild;
return p;
}
/*中序遍历求尾点*/
tree findEnd(tree t)
{
if(t==NULL) return t;
tree q=t;
while(q->rchild!=NULL) q=q->rchild;
return q;
}
int main()
{ tree t,t1;
t=createTree();
printf("\n中序遍历:\n");
intree(t);
printf("\n\n");
t1=findFir(t);
printf("中序遍历的首点:%c\n\n",t1->data);
t=findEnd(t);
printf("中序遍历的尾点:%c",t->data);
return 0;
}
#include <stdlib.h>
#define M 100
//前序遍历:ABD#E##FG###C##
typedef struct tree/*二叉树*/
{ char data;
struct tree *lchild,*rchild;
}bintree;
typedef bintree *tree;
tree createTree()/*前序遍历建树*/
{
tree t;
char c=getchar();
if(c=='#') return NULL;
else
{ t=(tree)malloc(sizeof(bintree));
t->data=c;
t->lchild=createTree();
t->rchild=createTree();
}
return t;
}
/*非递归中序遍历:思路:边遍历边输出,先输出左子树的最左边一个节点,并放入栈,*/
void intree(tree t)
{ tree stack[M];int top=0;/*定义、初始化栈*/
while(top||t)
{ if(t!=NULL)
{ stack[top++]=t;
t=t->lchild;
}else if(top!=0)
{ t=stack[--top];
printf("%c",t->data);
t=t->rchild;
}
}
}
/*中序遍历求首点*/
tree findFir(tree t)
{
if(t==NULL) return t;
tree p=t;
while(p->lchild!=NULL) p=p->lchild;
return p;
}
/*中序遍历求尾点*/
tree findEnd(tree t)
{
if(t==NULL) return t;
tree q=t;
while(q->rchild!=NULL) q=q->rchild;
return q;
}
int main()
{ tree t,t1;
t=createTree();
printf("\n中序遍历:\n");
intree(t);
printf("\n\n");
t1=findFir(t);
printf("中序遍历的首点:%c\n\n",t1->data);
t=findEnd(t);
printf("中序遍历的尾点:%c",t->data);
return 0;
}
相关文章推荐
- LeetCode_Best Time to Buy and Sell Stock
- 使用开源C++项目WebSocketpp构建web服务器
- 二叉树镜像(C++版)
- 有关于提高C/C++运行效率以及避免出现Bug的几种常见的实用方法
- 树的括号表示法(C语言版)
- C++ 表达式和运算符
- C++ 使用字符串
- LeetCode_Jump Game II
- 稀疏矩阵的快速转置(C语言版)
- 邻接表的实现与深度遍历
- 顺时针打印矩阵(C++版)
- C语言位运算符:与、或、异或、取反、左移和右移
- LeetCode_Jump Game
- C语言精华代码
- c++命令结束进程树
- C++中关于运算符 “.”和“->”的区分
- 【C语言提高12】间接赋值从0级指针到1级指针
- C语言根据路径打开文件内容
- codeforces 499B Lecture(map与string简单用法)
- 2015杭电新生赛1008游乐场【神坑】