【算法】【线性表】【数组】从中序与后序遍历序列构造二叉树

1  题目

给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。

示例 1:

输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]

示例 2:

输入:inorder = [-1], postorder = [-1]
输出:[-1]

提示:

  • 1 <= inorder.length <= 3000
  • postorder.length == inorder.length
  • -3000 <= inorder[i], postorder[i] <= 3000
  • inorder 和 postorder 都由 不同 的值组成
  • postorder 中每一个值都在 inorder 中
  • inorder 保证是树的中序遍历
  • postorder 保证是树的后序遍历

2  解答

在做这道题之前,你要知道中序和后序怎么推前序,以及前序、中序以及后序的二叉树遍历,这些二叉树的基础知识首先要知道,否则这题你就是给自己挖坑哈:

/**
 * Definition for a binary tree node.
 * public 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;
 *     }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] inOrder, int[] postOrder) {
       Map<Integer, Integer> inMap = new HashMap<>(inOrder.length);
        for (int i = 0; i < inOrder.length; i++) {
            inMap.put(inOrder[i], i);
        }
        return buildTree(inMap, 0, inOrder.length - 1, postOrder, 0, postOrder.length - 1);
    }

    public TreeNode buildTree(Map<Integer, Integer> inMap, int inLeft, int inRight, int[] postOrder, int poLeft, int poRight) {
        if (inLeft > inRight || poLeft > poRight) return null;
        int rootVal = postOrder[poRight];
        // 在中序确定左右子树位置
        Integer rootInIndex = inMap.get(rootVal);
        int sub = rootInIndex - inLeft;
        // 构建左子树
        TreeNode left = buildTree(inMap, inLeft, rootInIndex - 1, postOrder, poLeft, poLeft + sub - 1);
        // 构建右子树
        TreeNode right = buildTree(inMap, rootInIndex + 1, inRight, postOrder, poLeft + sub, poRight - 1);
        TreeNode root = new TreeNode(rootVal, left, right);
        return root;
    }
}

加油。

posted @ 2024-03-13 14:31  酷酷-  阅读(9)  评论(0编辑  收藏  举报