#include"stdafx.h"
#include<iostream>
#include<assert.h>
#include<stdlib.h>
using namespace std;
typedef int Elemtype;
typedef struct Tree{
Elemtype data; // 存放数据域
struct Tree *lchild; // 遍历左子树指针
struct Tree *rchild; // 遍历右子树指针
}BNode, *BTree;
BTree Creat_BiTree(){
int data;
cin >> data;
BNode* root = (BTree)malloc(sizeof(BNode));
if (data == -1) return NULL;
else{
root->data = data;
cout << "请输入" << data << "左节点的数值" << endl;
root->lchild = Creat_BiTree();
cout << "请输入" << data << "右节点的数值" << endl;
root->rchild = Creat_BiTree();
}
return root;
}
//先序排列
void PreOrder(BTree root){
if (root== NULL){
return;
}
cout << root->data << " ";
PreOrder(root->lchild);
PreOrder(root->rchild);
}
//中序排列
void InOrder(BTree root){
if (root == NULL){
return;
}
InOrder(root->lchild);
cout << root->data << " ";
InOrder(root->rchild);
}
//后续遍历
void PostOrder(BTree root){
if (root == NULL){
return;
}
PostOrder(root->lchild);
PostOrder(root->rchild);
cout << root->data << " ";
}
int sum = 0;
//先序遍历输出叶子节点
void Leaf(BTree root){
if (root == NULL) return;
if (root->lchild == NULL&&root->rchild == NULL){
cout << endl<<root->data << endl;
sum++;
}
Leaf(root->lchild);
Leaf(root->rchild);
}
//求二叉树的高度(递归算法)
void height(BTree root, int h,int *p){
if (root != NULL){
if (h > *p){
*p = h;
}
height(root->lchild , h + 1,p);
height(root->rchild, h + 1,p);
}
}
int main(){
cout << "请输入根节点的数值:" << endl;
BTree root = Creat_BiTree();
cout << "先序遍历" << endl;
PreOrder(root);
cout << endl;
cout << "中序遍历" << endl;
InOrder(root);
cout << endl;
cout << "后序遍历" << endl;
PostOrder(root);
cout << endl;
cout << "叶子节点为" ;
Leaf(root);
cout << "叶子节点个数为" << endl << sum;
int x=0;
height(root, 1,&x);
cout << endl << "二叉树的高度为:"<<x<< endl;
cout <<endl<< "容颜如玉,身姿如松,翩若惊鸿,婉若游龙。" << endl;
}
我爱柚子