java算法:递归二叉树算法

java算法:递归二叉树算法

二叉树的本质是递归结构,很多可以使用递归分治法完成的,推广了遍历算法。

在只给定指向树的一个指针的前提下,经常需要找到树的各种结构参数的值。

例1:树参数的计算,树的结点树和高度

Java代码 复制代码
  1. private static int count(Node h){   
  2.     if(h == null){   
  3.         reutrn 0;   
  4.     }   
  5.     return count(h.l) + count(h.r) + 1;   
  6. }   
  7. int count(){   
  8.     return count(root);   
  9. }   
  10. private static int height(Node h){   
  11.     if(h == null){   
  12.         return -1;   
  13.     }   
  14.     int u = height(h.l), v = height(h.r);   
  15.     if(u > v){   
  16.         return u + 1;   
  17.     }else{   
  18.         return v + 1;   
  19.     }   
  20. }   
  21. int height(){   
  22.     return height(root);   
  23. }  

例2:快速的输出树方法

Java代码 复制代码
  1. static void printNode(Item x, int h){   
  2.     for(int i = 0; i < h; i++){   
  3.         System.out.println("   ");   
  4.     }   
  5.     System.out.println("[" + x + "]");   
  6. }   
  7. private static void showR(Node t, int h){   
  8.     if(t == null){   
  9.         printNode(null, h);   
  10.         return;   
  11.     }   
  12.     showR(t.r, h + 1);   
  13.     printNode(t.item, h);   
  14.     showR(t.l, h + 1);   
  15. }   
  16. void show(){   
  17.     showR(root, 0);   
  18. }  

例3:竞标赛树的构建(分支递归策略)

Java代码 复制代码
  1. static class Node{   
  2.     double val;   
  3.     Node l;   
  4.     Node r;   
  5.     Node(double v, Node l, Node r){   
  6.         this.val = v;   
  7.         this.l = l;   
  8.         this.r = r;   
  9.     }   
  10. }   
  11. static Node max(double a[], int l, int r){   
  12.     int m = (l + r)/2;   
  13.     Node x = new Node(a[m], nullnull);   
  14.     if(l == r){   
  15.         return x;   
  16.     }   
  17.     x.l = max(a, l, m);   
  18.     x.r = max(a, m + 1, r);   
  19.     double u = x.l.val, v = x.r.val;   
  20.     if(u > v){   
  21.         x.val = u;   
  22.     }else{   
  23.         x.val = v;   
  24.     }   
  25.     return x;   
  26. }  

在某些情况下,构建递归数据结构可能要比通过扫描数据找到最大值好。

使二叉树构建前缀表达式。

前缀表达式

例4:解析树的构建

Java代码 复制代码
  1. static Node parse(){   
  2.     char t = a[i++];   
  3.     Node x = new Node(t);   
  4.     if((t == '+') || (t == '*')){   
  5.         x.l = parse();   
  6.         x.r = parse();   
  7.     }   
  8.     return x;   
  9. }  

编译程序如编译器经常使用这样的内部树来表示程序,树可以用于很多目的。

posted on 2012-11-01 10:00  吴一达  阅读(296)  评论(0编辑  收藏  举报

导航