[Offer] to prove safety 04 - reconstruction of a binary tree

Reconstruction of a binary tree

Time limit : 1秒
space constraints : 32768K
this question knowledge :
Title Description :

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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) {
        
    }
}

Analytical thinking:

Binary tree traversal has the following characteristics:

Traversal Abbreviated
Preorder root preLeft preRight Root around
Preorder inLeft root inRight Left and right root
Postorder post left postRight root Root around

Solution one:

/**
 * 将先序序列看作 root + preLeft + preRight 三个部分
 * 将中序序列看作 inLeft + root + inRight 三个部分
 *
 * 解题思路:二叉树根节点为初始先序序列的root,使用先序序列首元素拆分中序为左右两个部分,
 * 并根据 inLeft / inRight 的分别元素长度,拆分出 preLeft + preRight 序列 => 递归求解
 *
 * 返回条件:任意子树序列的长度(preLeft || preRight || inLeft || inRight)等于 0 
 */
import java.util.Arrays;
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        // 出口条件:子树序列长度为 0
        if(pre.length == 0 || in.length == 0){
            return null;
        }
        
        // 取先序序列的首元素为二叉树(包括其子树)的根结点 root
        TreeNode node = new TreeNode(pre[0]);
        
        for(int i=0; i<in.length; i++){
            if(pre[0] == in[i]){ // 找到 root 在中序序列中的位置
                // 此处关注中序的长度反求先序的长度:
                // inLeft.length = (i)-(0) = preLeft.length = (i+1)-(1)
                node.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i+1),Arrays.copyOfRange(in, 0, i));
                // 同理,
                // inRight.length = (in.length)-(i+1) = preLeft = (pre.length)-(i+1)
                node.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i+1, pre.length),Arrays.copyOfRange(in, i+1, in.length));
            }
        }
        return node;
    }
}
/**
 * Arrays.copyOfRange()  摘自 JDK8,注意 【】 内的描述
 * @param original the array from which a range is to be copied
 * @param from the initial index of the range to be copied, inclusive
 * @param to the final index of the range to be copied, 【exclusive】.
 * The length of the returned array will be 【 to - from 】.
 */
copyOfRange(T[] original, int from, int to);

Answer two:

/**
 * TODO =.= 今天肝不动了,先写一种吧
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        
    }
}

Guess you like

Origin www.cnblogs.com/jianminglin/p/11280103.html