剑指offer第二版-7.重建二叉树

描述:输入某二叉树的前序遍历和中序遍历结果,重建该二叉树。假设前序遍历或中序遍历的结果中无重复的数字。

思路:前序遍历的第一个元素为根节点的值,据此将中序遍历数组拆分为左子树+root+右子树,前序遍历数组拆分为root+左子树+右子树。再对左右子树进行同样的操作。

考点:对二叉树不同遍历方法的掌握。

/**
 * Copyright(C) 2019 Hangzhou Differsoft Co., Ltd. All rights reserved.
 *
 */
package com.java.offer;

import com.java.offer.tree.TraversalOfBinaryTree;
import com.java.offer.tree.TreeNode;

/**
 * @since 2019年2月18日 下午7:07:37
 * @author xuchao
 *
 * 重建二叉树:
 * 前序+中序,后续+中序可以完成重建,而前序+后序无法完成
 */
public class P7_ConstructBinaryTree {

    public static TreeNode<Integer> constructBinaryTree(int[] pre, int preStart, int preEnd, int[] in, int inStart, int inEnd) {
        if (preStart > preEnd || inStart > inEnd) {
            return null;
        }
        TreeNode<Integer> root = new TreeNode<Integer>(pre[preStart]);
        for (int i = inStart; i <= inEnd; i++) {
            if (in[i] == root.val) {
                root.left = constructBinaryTree(pre, preStart + 1, preStart + i - inStart, in, inStart, i - 1);
                root.right = constructBinaryTree(pre, preStart + i - inStart + 1, preEnd, in, i + 1, inEnd);
            }
        }
        return root;
    }
    
    public static void main(String[] args) {
        //        1
        //      /   \
        //     2     3
        //   /   \
        //  4     5
        // pre->12453 in->42513 post->45231
        int[] pre = { 1, 2, 4, 5, 3 };
        int[] in = { 4, 2, 5, 1, 3 };
        
        TreeNode<Integer> root = constructBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
        // 对重建后的树,进行前中后序遍历,验证是否正确
        System.out.println(TraversalOfBinaryTree.preorderRecursively(root));
        System.out.println(TraversalOfBinaryTree.inorderRecursively(root));
        System.out.println(TraversalOfBinaryTree.postorderRecursively(root));
        System.out.println(TraversalOfBinaryTree.levelorder(root));
    }
}

猜你喜欢

转载自www.cnblogs.com/chao-zjj/p/10402306.html