还可以,自己做得出来。
public TreeNode buildTree(int[] inorder, int[] postorder) { //用一个map来存储中序 int n = inorder.length; if(n == 0){ return null; }else if(n == 1){ return new TreeNode(inorder[0]); } Map<Integer,Integer> map = new HashMap<>(); for(int i = 0;i<n;i++){ map.put(inorder[i],i); } TreeNode root = new TreeNode(postorder[n-1]); //构建左子树 int i = map.get(postorder[n-1]); //找到根节点在中序遍历中的下标值 root.left = buildTree(inorder,postorder,0,i-1,0,i-1,map); //构建右子树 root.right = buildTree(inorder,postorder,i+1,n-1,i,n-2,map); return root; } private TreeNode buildTree(int[] inorder, int[] postorder, int in_start, int in_end, int post_start, int post_end,Map<Integer,Integer> map) { if(post_end < post_start){ return null; } TreeNode node = new TreeNode(postorder[post_end]); int i = map.get(postorder[post_end]); node.left = buildTree(inorder, postorder, in_start, i, post_start, post_start+i-in_start-1, map); node.right = buildTree(inorder, postorder, i+1, in_end, post_start+i-in_start, post_end-1, map); return node; }
——2020.7.1