Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Solution1: Recursive做法
Example:
1
2 3
4 5 6 7
8 9 10
In order: 8 4 9 2 5 1* 10 6 3 7
Post order: 8 9 4 5 2 10 6 7 3 1*
与105题 http://www.jianshu.com/p/50598ba9e342 类似
思路:
Postorder的最后一位是根节点,顺序:左树,右树,根节点;Inorder顺序:左树,根节点,右树。
利用此特性,每次在每一段postorder序列中,得到最后一位元素,在inorder序列中查找此元素位置pos,inorder序列中pos的前、后部分a(8 4 9 2 5)、b(10 6 3 7)分别作为下次递归的inorder序列input;
并利用a、b部分的长度/位置在postorder序列中找到相应部分c(8 9 4 5 2)、d(6 7 3 1),作为下次递归的postorder序列input。
重复此过程(Top-down Recursion)。
在inorder查找的过程利用hashmap,故
Time Complexity: O(N) Space Complexity: O(N)
1.b change End to 元素边界
Solution2: Iterative做法
思路:
Solution1.a Code:
class Solution1 {
private HashMap<Integer, Integer> inorder_map = new HashMap<Integer, Integer>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder == null || postorder == null || inorder.length != postorder.length)
return null;
// build hashmap from Inorder array
for (int i = 0; i < inorder.length; ++i) {
inorder_map.put(inorder[i], i);
}
// recursively build the tree
return build(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
}
public TreeNode build(int[] inorder, int in_start, int in_end, int[] postorder, int post_start, int post_end) {
if(in_start > in_end || post_start > post_end)
return null;
int root_value = postorder[post_end];
TreeNode root = new TreeNode(root_value);
int pos_inorder = inorder_map.get(root_value);
int post_left_length = pos_inorder - in_start;
root.left = build(inorder, in_start, pos_inorder - 1, postorder, post_start, post_start + post_left_length - 1);
root.right = build(inorder, pos_inorder + 1, in_end, postorder, post_start + post_left_length, post_end - 1);
return root;
}
}
Solution1.b Code:
change End to 元素边界
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if(inorder == null || postorder == null || inorder.length == 0 || postorder.length == 0) return null;
Map<Integer, Integer> in_map = new HashMap<>();
for(int i = 0; i < inorder.length; i++) {
in_map.put(inorder[i], i);
}
return dfsBuild(in_map, inorder, 0, inorder.length, postorder, 0, postorder.length);
}
private TreeNode dfsBuild(Map<Integer, Integer> in_map, int[] inorder, int in_s, int in_e, int[] postorder, int post_s, int post_e) {
if(in_s == in_e || post_s == post_e || post_e - 1 < 0) return null;
int cur_val = postorder[post_e - 1];
TreeNode root = new TreeNode(cur_val);
int in_index = in_map.get(cur_val);
int rela_in_index = in_index - in_s;
root.left = dfsBuild(in_map, inorder, in_s, in_index, postorder, post_s, post_s + rela_in_index);
root.right = dfsBuild(in_map, inorder, in_index + 1, in_e, postorder, post_s + rela_in_index, post_e - 1);
return root;
}
}
``