普通二叉树的构建与层次遍历
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;
}
前:“根左右"原则:先考虑根节点,再考虑左子树,最后为右子树,同时在左右子树中又坚持“根左右”原则。依次类推。
中后序遍历类似:中("左根右"),后("左右根");
#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++二叉树的构建及求深度,叶子数量,层次遍历
- java 实现二叉树的构建,先序,中序,后序,层次,递归,非递归的遍历
- java操作二叉树:构建二叉树;前序、中序、后续、层次遍历
- c++ 二叉树的构建 前序遍历 中序遍历 后续遍历 层次遍历
- 二叉树的构建、层次打印、广度遍历、深度遍历、K值路径
- 层次遍历构建二叉树
- 树 :二叉树(构建,遍历:层次,前序、中序、后序)学习总结
- 中序遍历,层次遍历构建二叉树
- 二叉树层次遍历
- 数据结构作业:利用中序遍历和后序遍历构建二叉树(RMQ转LCA)
- 二叉树系列二:二叉树的层次遍历(BFS)
- 已知二叉树的前序和中序遍历,构建该二叉树
- 按层打印二叉树的节点【层次遍历变形】
- 数据结构——二叉树的层次遍历
- 二叉树的层次遍历及其变型
- 二叉树层次遍历
- 二叉树层次遍历java
- LintCode-二叉树的层次遍历 II