105. 从前序与中序遍历序列构造二叉树

给定一棵树的前序遍历 preorder 与中序遍历  inorder。请构造二叉树并返回其根节点。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.HashMap;
import java.util.Map;

class Solution {

    private static TreeNode build(int[] preorder, int preStart, int preEnd, Map<Integer, Integer> inMap, int inStart, int inEnd) {
        if (preStart == preEnd) {
            return new TreeNode(preorder[preStart]);
        }

        if (preStart > preEnd) {
            return null;
        }

        int inVal = preorder[preStart];

        TreeNode root = new TreeNode(inVal);

        int inPos = inMap.get(inVal);

        int leftLength = inPos - inStart;
        int rightLength = inEnd - inPos;

        root.left = build(preorder, preStart + 1, preStart + leftLength, inMap, inStart, inPos - 1);
        root.right = build(preorder, preEnd - rightLength + 1, preEnd, inMap, inPos + 1, inEnd);

        return root;
    }

    public static TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || preorder.length == 0 || inorder == null || inorder.length == 0 || preorder.length != inorder.length) {
            return null;
        }
        Map<Integer, Integer> inMap = new HashMap<>();
        for (int i = 0; i < inorder.length; ++i) {
            inMap.put(inorder[i], i);
        }
        return build(preorder, 0, preorder.length - 1, inMap, 0, inorder.length - 1);
    }

    public static void main(String[] args) {
        int[] pre = {3, 9, 20, 15, 7};
        int[] in = {9, 3, 15, 20, 7};
        buildTree(pre, in);
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
上一篇:94. 二叉树的中序遍历


下一篇:22-lt-重建二叉树