LeetCode-106-从中序与后序遍历序列构造二叉树

题目

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

示例 1:

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

示例 2:

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

提示:

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

题解

至于这一题,没什么说法的,和105的思路是一致的,区别在于根节点的位置和递归时的区间边界:

后序遍历中最后一个节点为根节点;

递归左子树时,从后序遍历的左边界,到后序遍历左边界+左子树长度-1

递归右子树时,从后序遍历左边界+左子树长度,到后序遍历右边界-1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {

private Map<Integer, Integer> indexMap;

public TreeNode myBuildTree(int[] postorder, int[] inorder, int postorder_left, int postorder_right,
int inorder_left,
int inorder_right) {
if (postorder_left > postorder_right) {
return null;
}

// 后序遍历中的最后一个节点就是根节点
int postorder_root = postorder_right;
// 在中序遍历中定位根节点
int inorder_root = indexMap.get(postorder[postorder_root]);

// 先把根节点建立出来
TreeNode root = new TreeNode(postorder[postorder_root]);
// 得到左子树中的节点数目
int size_left_subtree = inorder_root - inorder_left;
// 递归地构造左子树,并连接到根节点
// 后序遍历中「从 左边界+1 开始的 size_left_subtree - 1」个元素就对应了中序遍历中「从 左边界 开始到 根节点定位-1」的元素
root.left = myBuildTree(postorder, inorder, postorder_left, postorder_left + size_left_subtree - 1,
inorder_left,
inorder_root - 1);
// 递归地构造右子树,并连接到根节点
// 后序遍历中「从 左边界+左子树节点数目 开始到 右边界 - 1」的元素就对应了中序遍历中「从 根节点定位+1 到 右边界」的元素
root.right = myBuildTree(postorder, inorder, postorder_left + size_left_subtree, postorder_right - 1,
inorder_root + 1, inorder_right);
return root;
}

public TreeNode buildTree(int[] inorder, int[] postorder) {
int n = postorder.length;
// 构造哈希映射,帮助我们快速定位根节点
indexMap = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
indexMap.put(inorder[i], i);
}
return myBuildTree(postorder, inorder, 0, n - 1, 0, n - 1);
}
}

LeetCode-106-从中序与后序遍历序列构造二叉树
https://excelius.xyz/leetcode-106-从中序与后序遍历序列构造二叉树/
作者
Ther
发布于
2024年7月25日
许可协议