一、题目粗心
给定两个整数数组 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 保障是树的后序遍历
起源:力扣(LeetCode)
链接:https://leetcode.cn/problems/...
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。
二、解题思路
要求从中序和后序遍历的后果来从新建原二叉树,中序遍历程序是左 根 右,后序遍历程序是左 右 根,对于这种树的重建个别采纳递归来做,因为后序的程序的最初一个必定是根,所以原二叉树的根节点能够晓得,题目中给了一个很要害的条件就是树中没有雷同元素,有了这个条件就能够在中序遍历中也定位出根节点的地位,并依据根节点的地位将中序遍历拆分为春熙路右两局部,别离对其递归调用原函数。
三、解题办法
3.1 Java实现
public class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { return helper(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1); } TreeNode helper(int[] in, int inL, int inR, int[] post, int postL, int postR) { if (inL > inR || postL > postR) { return null; } TreeNode node = new TreeNode(post[postR]); int i = 0; for (i = inL; i < in.length; i++) { if (in[i] == node.val) { break; } } node.left = helper(in, inL, i - 1, post, postL, postL + i - inL - 1); node.right = helper(in, i + 1, inR, post, postL + i - inL, postR - 1); return node; }}
四、总结小记
- 2022/10/7 今天又是新的一天