网站建设制作怎么弄,wordpress最好的系统,社交网站cms,兰州app定制开发106. 从中序与后序遍历序列构造二叉树
给定两个整数数组 inorder 和 postorder #xff0c;其中 inorder 是二叉树的中序遍历#xff0c; postorder 是同一棵树的后序遍历#xff0c;请你构造并返回这颗 二叉树 。 示例 1: 输入#xff1a;inorder [9,3,15,20,7], postor…106. 从中序与后序遍历序列构造二叉树
给定两个整数数组 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月20日每日一题使用递归分治对每个子树的中序和后序序列分别处理即可具体思路可见北邮复试刷题105. 从前序与中序遍历序列构造二叉树__递归分治 (力扣每日一题) 代码
/*** 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 {MapInteger,Integer map;public TreeNode buildTree(int[] inorder, int[] postorder) {map new HashMap();for(int i0;iinorder.length;i){map.put(inorder[i],i);}return myBuildTree(inorder,postorder,0,inorder.length-1,0,postorder.length-1);}public TreeNode myBuildTree(int[] inorder,int[] postorder,int inStart,int inEnd,int postStart,int postEnd){// 递归边界因某子树中序序列与后序序列长度相同 故选择一种判断即可if(inStart inEnd){return null;}TreeNode res new TreeNode(postorder[postEnd]);int post_in_inorder map.get(postorder[postEnd]);int placeLeft post_in_inorder-1 - inStart;res.left myBuildTree(inorder,postorder,inStart,post_in_inorder-1,postStart,placeLeftpostStart);int placeRight inEnd - (post_in_inorder1);res.right myBuildTree(inorder,postorder,post_in_inorder1,inEnd,postEnd-1-placeRight,postEnd-1);return res;}
}结果