Prove safety Offer -. 4 binary tree reconstruction

Title Description

And enter the result in a preorder traversal of a binary tree in preorder traversal of the binary tree a rebuild. Suppose Results preorder traversal order and input of duplicate numbers are free. Before entering e.g. preorder traversal sequence {1,2,4,7,3,5,6,8} and {4,7,2,1,5,3,8,6} order traversal sequence, and the reconstructed binary tree return.

Ideas and Implementation

 * 题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历结果中都不含重复的数字。 
 * 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建出下图的二叉树并输出他的根节点。
 *                     1
 *                   /   \
 *                  2     3
 *                 /     / \
 *                4     5   6
 *                 \        /
 *                 7        8

The first value is the value of the preorder traversal of the root node, this value will be used in order traversal results divided into two parts, the left part of the left subtree of the tree in preorder a result, the right part of the right subtree of the tree in preorder the result of.

/**
 * 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) {
        TreeNode root = reBuilt(pre, 0, pre.length - 1, 
                               in, 0, in.length - 1);
        return root;
    }
    
    //递归含义,返回给定的前序遍历和中序遍历所组成的树的根节点
    private TreeNode reBuilt(int[] pre, int startPre, int endPre, 
                            int[] in, int startIn, int endIn) {
        //递归终止条件
        if (startPre > endPre || startIn > endIn) {
            return null;
        }
        
        TreeNode root = new TreeNode(pre[startPre]);
        
        for (int i = startIn; i <= endIn; i++) {
            if (in[i] == pre[startPre]) {
                //重点,里面的起始值和结束值
                //左子树:前序遍历中起始值为之前的起始值加一,终点值为前序起始值加上(中序的根值i-中序的起始值,即得到左子树个数)
                //中序遍历中起始值为之前中序起始值,终点值为中序根结点减一即i-1
                root.left = reBuilt(pre, startPre + 1, startPre + i - startIn, 
                                   in, startIn, i - 1);
                //右子树:前序遍历中起始值为前序起始值加上左子树个数(i-startIn)再加1,终点值为前序的终点值。
                //中序遍历中起始值为中序根结点加一(i+1),终点值为之前中序的终点值
                root.right = reBuilt(pre, startPre + (i - startIn + 1), endPre, in, i + 1, endIn);
            }
        }
        
        return root;
    }
}

Guess you like

Origin www.cnblogs.com/xiehang/p/11274077.html