#include<bits/stdc++.h>
using namespace std;
typedef char eletype;
typedef struct node{
struct node *left;
struct node *right;
eletype value;
}treenode,*tree;
//1.求树的高度(后序遍历求树的高度)
int requestTreehigh(tree root){
int lefthigh,righthigh,maxhigh;//定义左子树高右子树高
if(root!=NULL){
lefthigh=requestTreehigh(root->left);//递归求左子树高
righthigh=requestTreehigh(root->right);//递归求右子树高
maxhigh=lefthigh>righthigh?lefthigh:righthigh;//求最高的子树高度
return maxhigh+1;//本层高度等于最高子树高度加一
}
else{
return 0;
}
}
//2.求树的高度(先序遍历求树的高度)
int depth=0;
int PrerequestTreehigh(tree root,int h){
if(root!=NULL){
if(h>depth) depth=h;
PrerequestTreehigh(root->left,h+1);
PrerequestTreehigh(root->right,h+1);
}
}
//建树
void crtTreenode(tree *root){
char ch=getchar();
getchar();
if(ch=='/'){
*root=NULL;
}
else{
(*root)=new treenode;
(*root)->value=ch;
crtTreenode(&(*root)->left);
crtTreenode(&(*root)->right);
}
}
int main()
{
cout<<"建立树:"<<endl;
tree p;
crtTreenode(&p);
cout<<endl;
cout<<"后序看高:"<<endl;
int high=requestTreehigh(p);
cout<<high<<endl;
cout<<"先序看高:"<<endl;
PrerequestTreehigh(p,1);
int highs=depth;
cout<<depth<<endl;
}
运行结果如图:
欢迎参考学习。