剑指offer-重建二叉树

题目:重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

思路:晚上来道基础题热热手,就是利用了前序遍历的第一个是根节点,然后在中序遍历中找到根节点的位置,则根节点之前的为左子树,根节点以后的为右子树,然后递归循环就行。

 1 public class Solution {
 2     public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
 3         TreeNode root= reConstructBinTree(pre,0,pre.length-1,in,0,in.length-1);
 4         return root;       
 5     }
 6     private TreeNode reConstructBinTree(int []pre,int preStart,int preEnd,int[]in,int inStart,int inEnd){
 7         if(preStart>preEnd||inStart>inEnd)
 8             return null;
 9         TreeNode root=new TreeNode(pre[preStart]);
10         for(int i=inStart;i<=inEnd;i++){
11             if(in[i]==pre[preStart]){
12                 //利用前序遍历的首个是根节点的特点,在中序遍历里找到根节点的位置,那么在根节点以前的就属于左子树,
13                 //根节点以后的就属于右子树,然后循环递归就行
14                 root.left=reConstructBinTree(pre,preStart+1,preStart+i-inStart,in,inStart,i-1);
15                 root.right=reConstructBinTree(pre,preStart+i-inStart+1,preEnd,in,i+1,inEnd);
16             }
17         }
18         return root;
19     }
20 }
原文地址:https://www.cnblogs.com/pathjh/p/9131394.html