java算法:递归二叉树算法
二叉树的本质是递归结构,很多可以使用递归分治法完成的,推广了遍历算法。
在只给定指向树的一个指针的前提下,经常需要找到树的各种结构参数的值。
例1:树参数的计算,树的结点树和高度
Java代码
privatestaticintcount(Node h){
if(h ==null){
reutrn0;
}
returncount(h.l) + count(h.r) +1;
}
intcount(){
returncount(root);
}
privatestaticintheight(Node h){
if(h ==null){
return-1;
}
intu = height(h.l), v = height(h.r);
if(u > v){
returnu +1;
}else{
returnv +1;
}
}
intheight(){
returnheight(root);
}
private static int count(Node h){
i