您的位置:首页 > 其它

普通二叉树的构建与层次遍历

2017-09-25 20:06 363 查看
树的遍历分为前,后,中序。
前:“根左右"原则:先考虑根节点,再考虑左子树,最后为右子树,同时在左右子树中又坚持“根左右”原则。依次类推。
 中后序遍历类似:中("左根右"),后("左右根");
#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;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: