剑指 Offer——4. 重建二叉树

题目描述

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

思路与实现

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

前序遍历的第一个值为根节点的值,使用这个值将中序遍历结果分成两部分,左部分为树的左子树中序遍历结果,右部分为树的右子树中序遍历的结果。

/**
 * 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;
    }
}

猜你喜欢

转载自www.cnblogs.com/xiehang/p/11274077.html