树的遍历分为前,后,中序。
前:“根左右"原则:先考虑根节点,再考虑左子树,最后为右子树,同时在左右子树中又坚持“根左右”原则。依次类推。
中后序遍历类似:中("左根右"),后("左右根");
#include<iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef struct TreeNode{
int data;
struct TreeNode *lchild;
struct TreeNode *rchild;
int ltag,rtag;
}*Tree;
Tree Cteate_Tree(Tree t){
char a;
scanf("%c",&a);
if(a!='#'){
t = (Tree)malloc(sizeof(Tree));
t->data = a; //建立根节点
printf("%c'lchild is\n",a);
getchar();
t->lchild = Cteate_Tree(t->lchild) ; //递归建立左字树
printf("%c'rchild is\n",a);
getchar();
t->rchild = Cteate_Tree(t->rchild) ; //递归建立右字树
}
else{
return NULL;
}
return t;
}
/*中序遍历*/
void InOrder(Tree t){
if(t){
InOrder(t->lchild);
printf("%c ",t->data);
InOrder(t->rchild);
}
}
int main(){
Tree t;
t = Cteate_Tree(t);
InOrder(t);
return 0;
}
本文介绍了一种使用C语言实现树的中序遍历的方法。通过递归方式创建二叉树,并采用中序遍历(左根右)的方式打印出树的节点。文章提供了完整的代码示例,包括树节点的定义、树的创建过程及遍历函数。
2394

被折叠的 条评论
为什么被折叠?



