#include <iostream>
using namespace std;
typedef char ElemType;typedef struct BiNode {//节点的创建ElemType data;struct BiNode *lchild, *rchild;
} BiNode, *BiTree;void PreOrderTraverse(BiTree T) {//先序遍历if (T) {cout << T->data;PreOrderTraverse(T->lchild);PreOrderTraverse(T->rchild);}
}void InOrderTraverse(BiTree T) {//中序遍历if (T) {InOrderTraverse(T->lchild);cout << T->data;InOrderTraverse(T->rchild);}
}void PostOrderTraverse(BiTree T) {//后序遍历if (T) {PostOrderTraverse(T->lchild);PostOrderTraverse(T->rchild);cout << T->data;}
}void CreateBiTree(BiTree &T) {//创建二叉树char ch;cin >> ch;if (ch == '#')T = NULL;else {T = new BiNode;T->data = ch;CreateBiTree(T->lchild);CreateBiTree(T->rchild);}
}void Copy(BiTree T, BiTree &NewT) {//复制出一个新的二叉树if (T == NULL) {NewT = NULL;return ;} else {NewT = new BiNode;NewT->data = T->data;Copy(T->lchild, NewT->lchild);Copy(T->rchild, NewT->rchild);}
}int Depth(BiTree T) {//求深度if (T == NULL)return 0;else {int m = Depth(T->lchild);int n = Depth(T->rchild);if (m > n)return (m + 1);elsereturn (n + 1);}
}int NodeCount(BiTree T) {//求节点的个数if (T == NULL)return 0;elsereturn NodeCount(T->lchild) + NodeCount(T->rchild) + 1;
}int LeafCount(BiTree T) {//求叶子的个数if (T == NULL)return 0;if (T->lchild == NULL && T->rchild == NULL)return 1;elsereturn LeafCount(T->lchild) + LeafCount(T->rchild);
}int main() {BiTree T;//创建一颗二叉树cout << "以先序遍历输入(以#结束)要存储的元素" << endl;CreateBiTree(T);cout << "先序遍历输出: ";PreOrderTraverse(T);cout<<endl;cout << "中序遍历输出: ";InOrderTraverse(T);cout<<endl;cout << "后序遍历输出" ;PostOrderTraverse(T);cout<<endl;cout << "该树的深度为: ";cout << Depth(T) << endl;cout << "该树的节点个数为: ";cout << NodeCount(T) << endl;cout << "该树的叶子个数为: ";cout << LeafCount(T) << endl;system("pause");return 0;
}
测试效果图:
测试结果:
本文参考文章地址:
https://blog.csdn.net/deaidai/article/details/71834241