java算法:递归二叉树算法
二叉树的本质是递归结构,很多可以使用递归分治法完成的,推广了遍历算法。
在只给定指向树的一个指针的前提下,经常需要找到树的各种结构参数的值。
例1:树参数的计算,树的结点树和高度
- privatestaticintcount(Nodeh){
- if(h==null){
- reutrn0;
- }
- returncount(h.l)+count(h.r)+1;
- }
- intcount(){
- returncount(root);
- }
- privatestaticintheight(Nodeh){
- 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){
if(h == null){
reutrn 0;
}
return count(h.l) + count(h.r) + 1;
}
int count(){
return count(root);
}
private static int height(Node h){
if(h == null){
return -1;
}
int u = height(h.l), v = height(h.r);
if(u > v){
return u + 1;
}else{
return v + 1;
}
}
int height(){
return height(root);
}
例2:快速的输出树方法
- staticvoidprintNode(Itemx,inth){
- for(inti=0;i<h;i++){
- System.out.println("");
- }
- System.out.println("["+x+"]");
- }
- privatestaticvoidshowR(Nodet,inth){
- if(t==null){
- printNode(null,h);
- return;
- }
- showR(t.r,h+1);
- printNode(t.item,h);
- showR(t.l,h+1);
- }
- voidshow(){
- showR(root,0);
- }
static void printNode(Item x, int h){
for(int i = 0; i < h; i++){
System.out.println(" ");
}
System.out.println("[" + x + "]");
}
private static void showR(Node t, int h){
if(t == null){
printNode(null, h);
return;
}
showR(t.r, h + 1);
printNode(t.item, h);
showR(t.l, h + 1);
}
void show(){
showR(root, 0);
}
例3:竞标赛树的构建(分支递归策略)
- staticclassNode{
- doubleval;
- Nodel;
- Noder;
- Node(doublev,Nodel,Noder){
- this.val=v;
- this.l=l;
- this.r=r;
- }
- }
- staticNodemax(doublea[],intl,intr){
- intm=(l+r)/2;
- Nodex=newNode(a[m],null,null);
- if(l==r){
- returnx;
- }
- x.l=max(a,l,m);
- x.r=max(a,m+1,r);
- doubleu=x.l.val,v=x.r.val;
- if(u>v){
- x.val=u;
- }else{
- x.val=v;
- }
- returnx;
- }
static class Node{
double val;
Node l;
Node r;
Node(double v, Node l, Node r){
this.val = v;
this.l = l;
this.r = r;
}
}
static Node max(double a[], int l, int r){
int m = (l + r)/2;
Node x = new Node(a[m], null, null);
if(l == r){
return x;
}
x.l = max(a, l, m);
x.r = max(a, m + 1, r);
double u = x.l.val, v = x.r.val;
if(u > v){
x.val = u;
}else{
x.val = v;
}
return x;
}
在某些情况下,构建递归数据结构可能要比通过扫描数据找到最大值好。
使二叉树构建前缀表达式。
例4:解析树的构建
- staticNodeparse(){
- chart=a[i++];
- Nodex=newNode(t);
- if((t=='+')||(t=='*')){
- x.l=parse();
- x.r=parse();
- }
- returnx;
- }
static Node parse(){
char t = a[i++];
Node x = new Node(t);
if((t == '+') || (t == '*')){
x.l = parse();
x.r = parse();
}
return x;
}
编译程序如编译器经常使用这样的内部树来表示程序,树可以用于很多目的。