做网站要不要买服务器,网站开发架构师,昊客网络,合山网站建设思路#xff1a; 我觉得这种题还是要找好边界#xff0c;这道题和从中序和前序遍历序列构造二叉树差不多#xff0c;就是后序遍历和前序遍历是反着来的#xff0c;后序遍历最后一个是头节点#xff0c;然后递归时中序遍历的处理逻辑没什么变化#xff0c;唯一有变化的是后…思路 我觉得这种题还是要找好边界这道题和从中序和前序遍历序列构造二叉树差不多就是后序遍历和前序遍历是反着来的后序遍历最后一个是头节点然后递归时中序遍历的处理逻辑没什么变化唯一有变化的是后序遍历的递归逻辑在后序遍历中确认左子树和右子树的范围左子树范围是头节点---头节点左子树长度-1右子树范围头节点左子树长度---尾节点-1。 代码
/*** 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 i 0; i inorder.length; i) {map.put(inorder[i], i);}return helper(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1);}public TreeNode helper(int[] inorder, int[] postorder, int i_start, int i_end, int p_start, int p_end) {if (p_start p_end)return null;TreeNode root new TreeNode(postorder[p_end]);int mid map.get(postorder[p_end]);int leftLength mid - i_start;root.left helper(inorder, postorder, i_start, mid - 1, p_start, p_start leftLength - 1);root.right helper(inorder, postorder, mid 1, i_end, p_start leftLength, p_end - 1);return root;}
}