高校网站建设 调查,四川高端网站建设,企业网站备案要多少钱,西安哪家网络公司做网站给定两个整数数组 inorder 和 postorder #xff0c;其中 inorder 是二叉树的中序遍历#xff0c; postorder 是同一棵树的后序遍历#xff0c;请你构造并返回这颗 二叉树 。
思路#xff1a;
中序遍历数组中#xff0c;找到一个根节点#xff0c;那么其前为其左子树其中 inorder 是二叉树的中序遍历 postorder 是同一棵树的后序遍历请你构造并返回这颗 二叉树 。
思路
中序遍历数组中找到一个根节点那么其前为其左子树其后为其右子树后序遍历数组从后像前依次为 根节点-右-左根据后序数组得到根节点通过map保存inorder数据及下标以便返回根节点在inorder中的位置从而区分左右子树以便再次进行递归找到inorder中的根节点位置将其值加入到root中。
class Solution{int post_idx;int[] inorder;int[] postorder;MapInteger, Integer map new HashMap();public TreeNode buildTree(int[] inorder, int[] postorder){this.inorder inorder;this.postorder postorder;post_idx postorder.length - 1;int idx 0;// 将中序数组传进map中for(int val : inorder){map.put(val, idx);}return helper(0, post_idx);} public TreeNode helper(int l, int r){if(l r) return null;int root_val postorder[post_idx--];// 没有post_idx--,报错了StackOverflowErrorTreeNode root new TreeNode(root_val);int idx map.get(root_val);root.right helper(idx 1, r);root.left helper(l, idx - 1);return root;}
}