[数据结构] 二叉树的建立及其基本操作
2014-05-28 19:16
501 查看
如图:
代码:
运行截图:
注意输入的时候G后面还有两个空格
代码:
#include <iostream> #include <stdio.h> #include <algorithm> #include <string.h> using namespace std; char ch; typedef struct BinNode { char data; struct BinNode *lchild,*rchild; }BinNode,*BinTree; //二叉树链式存储结构 void CreateBinTree(BinTree &T)//先序建立二叉树 { ch=cin.get(); if(ch==' ') T=NULL; else if(ch=='\n') return; else { T=(BinNode*)malloc(sizeof(BinNode)); T->data=ch;//这是根节点 CreateBinTree(T->lchild);//创建左孩子 CreateBinTree(T->rchild);//创建右孩子 } } void PreOrder(BinTree T)//前序遍历二叉树 { if(T!=NULL) { cout<<T->data; PreOrder(T->lchild); PreOrder(T->rchild); } } void InOrder(BinTree T)//中序遍历二叉树 { if(T!=NULL) { InOrder(T->lchild); cout<<T->data; InOrder(T->rchild); } } void PostOrder(BinTree T)//后序遍历二叉树 { if(T!=NULL) { PostOrder(T->lchild); PostOrder(T->rchild); cout<<T->data; } } int cnt=0; int countNode(BinTree T)//求二叉树中节点的个数 { if(T) { cnt++; countNode(T->lchild); countNode(T->rchild); } return cnt; } int depthval=0; int dl=0; int dr=0; int Depth(BinTree T)//求二叉树的高度 { if(!T) return 0; else { dl=Depth(T->lchild); dr=Depth(T->rchild); depthval=1+(dl>dr?dl:dr); return depthval; } } int main() { //freopen("in.txt", "r", stdin); BinTree T; cout<<"按照先序次序输入二叉树各个节点的元素值,叶子节点为空用空格表示:"<<endl; CreateBinTree(T); cout<<"先序遍历二叉树为:"<<endl; PreOrder(T); cout<<endl; cout<<"中序遍历二叉树为:"<<endl; InOrder(T); cout<<endl; cout<<"后序遍历二叉树为:"<<endl; PostOrder(T); cout<<endl; cout<<"二叉树中节点的个数为:"<<endl; cout<<countNode(T)<<endl; cout<<"二叉树的深度为:"<<endl; cout<<Depth(T)<<endl; return 0; }
运行截图:
注意输入的时候G后面还有两个空格
相关文章推荐
- 二叉树的建立及其基本操作
- 二叉树建立及其基本操作
- 数据结构类型定义及基本操作汇总(二)-- 二叉树及其遍历
- 一步一步复习数据结构和算法基础-二叉树基本操作
- C++二叉树结构的建立与基本操作
- 数据结构:树与二叉树_二叉树_二叉树的基本操作
- 基本数据结构:建立二叉树 和 二叉树的顺序遍历
- 实验三 二叉树的基本操作(建立)及遍历
- 数据结构复习-二叉树基本操作
- 二叉树的建立和基本操作
- 二叉树的建立和基本操作<一>
- 二叉树基本操作的递归实现(二叉树建立,先序,中序,后序,深度的递归遍历。广度优先,高度优先的非递归遍历)
- 【数据结构】二叉树的基本操作
- 二叉树的建立和基本操作
- 二叉树的基本操作(定义、遍历、高度、生成)【数据结构】
- 二叉树的建立与基本操作
- 八.二叉树各种操作的C语言实现 树的一些基本的操作,包括,树的建立,树的深度,
- javascript实现数据结构: 树和二叉树,二叉树的遍历和基本操作
- 二叉树的建立(非递归建立与定义建立)与基本操作(广度和深度遍历,求叶子树高)实现
- 实验三 二叉树的基本操作(建立)及遍历