WenJieWangFlyToWorld

导航

8 根据前序遍历和中序遍历得到二叉树

  1. /** 
  2.  * 前序遍历和中序遍历创建二叉树  
  3.           Pre 前序遍历的数组 In 中序遍历的数组 lpre 前序遍历数组开始位置 hpre前序遍历结束位置 
  4.  * lin前序遍历数组开始位置 hin前序遍历结束位置 
  5.  */  
  6. @Override  
  7. public TreeNode PreInCreat(int[] Pre, int[] In, int lpre, int hpre, int lin, int hin) {  
  8.     TreeNode root = new TreeNode(0);  
  9.     if (Pre.length == 0 || In.length == 0) {  
  10.         return null;  
  11.     }  
  12.     root.val = Pre[lpre];  
  13.     int i;  
  14.     for (i = lin; In[i] != Pre[lpre]; i++)  
  15.         ;// 得到中序遍历数组的根节点位置  
  16.     int lleng = i - lin;// 左边子树的长度  
  17.     int rleng = hin - i;// 右边子树的长度  
  18.     
  19.     if (lleng > 0) {  
  20.         root.leftchild = PreInCreat(Pre, In, lpre + 1, lpre + lleng, lin, lin + lleng - 1);  
  21.     
  22.     } else {  
  23.         root.leftchild = null;  
  24.     }  
  25.     if (rleng > 0) {  
  26.         root.rightchild = PreInCreat(Pre, In, hpre - rleng + 1, hpre, hin - rleng + 1, hin);  
  27.     
  28.     } else {  
  29.         root.rightchild = null;  
  30.     }  
  31.     
  32.     return root;  
  33. }  

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