/* * @Issue: 二叉树的创建,遍历,删除 * @Author: 一届书生 * @LastEditTime: 2020-02-22 15:16:22 */ #include<iostream> using namespace std; // 定义树的基本结构 typedef struct CSNode{ char data; CSNode *left,*right; }TNode,*Tree; // 构造二叉树 [先序遍历输入的方法] void CreateTree(Tree &t){ char c; cin>>c; if(c=='#')t=NULL; else{ t=new TNode; t->data=c; CreateTree(t->left); CreateTree(t->right); } } //先序遍历[递归] void PreOrderTraverse(Tree T) { if(T) { cout<<T->data; PreOrderTraverse(T->left); PreOrderTraverse(T->right); } } //中序遍历[递归] void InOrderTraverse(Tree T) { if(T) { InOrderTraverse(T->left); cout<<T->data; InOrderTraverse(T->right); } } //后序遍历[递归] void PostOrderTraverse(Tree T) { if(T) { PostOrderTraverse(T->left); PostOrderTraverse(T->right); cout<<T->data; } } // 求二叉树的深度[递归] int getDepth(Tree t){ if(t==NULL) return 0; else{ int m=getDepth(t->left); int n=getDepth(t->right); return m>n?m+1:n+1; } } // 统计二叉树中结点的个数[递归] int getNodenum(Tree t){ if(t==NULL) return 0; else{ return getNodenum(t->left)+getNodenum(t->right)+1; } } // 统计二叉树中叶子结点的个数[递归] int getLeafnum(Tree t){ if(t==NULL) return 0; if(!t->left&&!t->right) return 1; //左右子树都不存在,即为叶节点 else{ return getLeafnum(t->left)+getLeafnum(t->right); } } int main(){ // 样例:AB#CD##E##F#GH### Tree t; CreateTree(t); cout<<endl<<"先序遍历输出:"; PreOrderTraverse(t); cout<<endl<<"中序遍历输出:"; InOrderTraverse(t); cout<<endl<<"后序遍历输出:"; PostOrderTraverse(t); cout<<endl<<"二叉树的深度为:"<<getDepth(t); cout<<endl<<"结点的个数为:"<<getNodenum(t); cout<<endl<<"叶子结点的个数为:"<<getLeafnum(t); return 0; }