一个记录父亲节点的数组:
如A【】={-1,0,0,1,1,2,2,3,3,3,7,11}
即是说A[0]没父亲所以为-1 A【1】父亲为A【0】,A【2】父亲也为A【0】,A【3】父亲为A【1】......
求这棵树的最高的高度??
//由于是全部遍历,如果简单全部遍历那么有很多重复的地方,那么可以利用动归迭代改进的方法:如果一个节点遍历的时候其父亲已经被计算过树高了那么就直接hight+=父亲.hight就行了,不要继续向上走了。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int tree_h(int *A,int len){
int max=0,hight,i;
int cord[len],temp;
memset(cord,-1,len);
for(i=0;i<len;i++)
{
temp=i;
hight=1;
while(A[temp]!=-1) {
if(cord[A[temp]]!=-1){
hight+=cord[A[temp]];
break;
}
hight++;
temp=A[temp];
}
cord[i]=hight;
if(hight>max)
{
max=hight;
}
}
return max;
}
void main(){
int A[13]={-1,0,0,1,1,2,2,3,3,3,7,9,8};
printf("%d",tree_h(A,13));
}
模板函数:当用默认值为模板类的参数的时候一定要显式声明 因为如果不声明默认的值就不知道是什么类型;
template<typename T1,typename T2>
void foobar(T1 a,T2 b=0){
// printf("%d",a);
}
int main(){
foobar<int,double>(1);// 如果是foobar(1)这样是错误的
return 0;
}
//判断是不是搜索树的后根遍历顺序,如果是就输出1,否则输出0
#include <iostream>
using std::cout
int right_tree,left_tree;
int justy(int start,int end, int *aid)//判断是不是搜索树的后根遍历顺序,如果是就输出1,否则输出0
{
if(start==end) return 1;//当自由一个节点的时候那就当它已经是满足条件了
int start_temp,end_temp;
for(start_temp=start;start_temp<end;start_temp++)//找左边的子树
if(aid[start_temp]>=aid[end])
break;
for(end_temp=start_temp;end_temp<end;end_temp++)//找右边的子树
if(aid[end_temp]<aid[end])
return 0;
if(start>=(start_temp-1))//如果它是有左子树的时候就执行它
left_tree=justy(start,start_temp-1,aid);
if(start_temp>=end-1)//如果它是有右子树的时候就执行它
right_tree=justy(start_temp,end-1,aid);
return left_tree&&right_tree;
}
int main()
{
int a[11]={2,4,3,8,9,7,5,11,14,12,10};//判断是不是搜索树的后根遍历顺序,如果是就输出1,否则输出0;
cout<<justy(0,10,a);
return 0;
}