唯一确认一棵二叉树

这个要通过递归来做,
如:给一个前序遍历{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
解题思路:
  1.先通过前序序列确认根节点(即数组的第一个),再通过中序序列确认左右子树
   2.分别对左右子树来进行递归,直到左右子树变为叶子节点为止

代码如下:
class TreeNode {
   int val;
    TreeNode left;
   TreeNode right;
    TreeNode(int x) { val = x; }
}

public class Solution {
     public TreeNode reConstructBinaryTree( int [] pre, int [] in) {
         TreeNode tree= new TreeNode(pre[ 0 ]);
         if (pre.length> 1 ){
             int count= 0 ;
             for ( int i= 0 ;i<in.length;i++)
                 {
                   if (in[i]==pre[ 0 ]) break ;
                   count++;               
                 }
             if (count> 0 ){
             int pre1[]= new int [count];
             int in1[]= new int [count];
             for ( int i= 1 ;i<=count;i++)
                 {
                   pre1[i- 1 ]=pre[i];
                }
              for ( int i= 0 ;i<count;i++)
                  {
                   in1[i]=in[i];  
               }
               tree.left=reConstructBinaryTree(pre1,in1);
             }
             if (pre.length-count- 1 > 0 ){
              int pre2[]= new int [pre.length-count- 1 ];
              int in2[]= new int [pre.length-count- 1 ];
               for ( int i=count+ 1 ;i<pre.length;i++)
                   {
                      pre2[i-count- 1 ]=pre[i];
                      in2[i-count- 1 ]=in[i];
                  }
                 tree.right=reConstructBinaryTree(pre2,in2);
             }
         }
         return tree; 
     }
}

版权声明:本文为YangOuBaDreams原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。