题目
给定两个整数数组 inorder
和 postorder
,其中 inorder
是二叉树的中序遍历, postorder
是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
示例 1:
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
inorder
和 postorder
都由 不同 的值组成
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; root.left = myBuildTree(postorder, inorder, postorder_left, postorder_left + size_left_subtree - 1 , inorder_left, inorder_root - 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 ); } }