WenJieWangFlyToWorld

导航

9 根据中序遍历和后序遍历得到二叉树

  1. public TreeNode InPostCreat(int[] In, int[] Post, int lin, int hin, int lpost, int hpost) {  
  2.         TreeNode root = new TreeNode(0);  
  3.         if (Post.length == 0 || In.length == 0) {  
  4.             return null;  
  5.         }  
  6.         root.val = Post[hpost];  
  7.         int i;  
  8.         for (i = lin; In[i] != Post[hpost]; i++)  
  9.             ;// 得到中序遍历数组的根节点位置  
  10.     
  11.         int lleng = i - lin;  
  12.         int rleng = hin - i;  
  13.     
  14.         if (lleng > 0) {  
  15.             root.leftchild = InPostCreat(In, Post, lin, lin + lleng - 1, lpost, lpost + lleng - 1);  
  16.         } else {  
  17.             root.leftchild = null;  
  18.         }  
  19.         if (rleng > 0) {  
  20.             root.rightchild = InPostCreat(In, Post, hin - rleng + 1, hin, hpost - rleng, hpost - 1);  
  21.         } else {  
  22.             root.rightchild = null;  
  23.         }  
  24.         return root;  
  25.     }  

posted on 2017-05-29 21:21  WenjieWangFlyToWorld  阅读(204)  评论(0编辑  收藏  举报