原题网址:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
方法:自顶向下,根据遍历特性构造。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private Map<Integer, Integer> im;
private TreeNode build(int[] inorder, int[] postorder, int infrom, int pofrom, int len) {
if (len <= 0) return null;
TreeNode root = new TreeNode(postorder[pofrom+len-1]);
if (len == 1) return root;
int i = im.get(postorder[pofrom+len-1]);
int left = i - infrom;
if (left > 0) root.left = build(inorder, postorder, infrom, pofrom, left);
if (len - left - 1 > 0) root.right = build(inorder, postorder, infrom + left + 1, pofrom + left, len - left - 1);
return root;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
im = new HashMap<>();
for(int i=0; i<postorder.length; i++) im.put(inorder[i], i);
return build(inorder, postorder, 0, 0, postorder.length);
}
}