题目描述

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

代码实现

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    //当然了,最好的做法是不需要构造数组,直接在原数组上进行操作,为此我们需要一个指针来做定位
    //前序遍历得到的数组,第一个元素就是根元素
    //中序遍历得到的数组,一旦确立根元素的位置,其左右两边分别是对应的左子树和右子树
   // 递归思想一定要熟悉掌握


    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if(pre.length == 0 || in.length == 0){
            return null;
        }
        TreeNode root =  reConstructBinaryTree(pre, 0 , pre.length - 1, in , 0 , in.length - 1);
        return root;
    }
    public TreeNode reConstructBinaryTree(int [] pre, int preStart, int preEnd, int [] in, int inStart,int inEnd) {
        if(preStart > preEnd || inStart > inEnd){
            return null;
        }
        TreeNode node = new TreeNode(pre[preStart]);
        for(int i = 0 ; i <= inEnd ; ++ i){
            if(in[i] == node.val){
                // 左子树的长度为 i - inStart
                // 所以新的 preEnd = preStart + 左子树的长度 = preStart + i - inStart
                node.left = reConstructBinaryTree(pre, preStart + 1 , preStart + i - inStart , in ,inStart, i -1);
                node.right = reConstructBinaryTree(pre, preStart + i - inStart + 1, preEnd , in ,i + 1, inEnd);
                break;
            }
        }
        return  node;
    }
}