Return any binary tree that matches the given preorder and postorder traversals.
Values in the traversals pre
and post
are distinct positive integers.
Example 1:
Input: pre = [1,2,4,5,3,6,7], post = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]
思路:Preorder: current, left, right : 1, (2, 4, 5 ), (3,6,7)
Postorder: left, right, current: (4,5,2), (6,7,3), 1
破題口是在2上面,pre[pstart + 1] 在postorder 裏面是left的最後一個index,從而可以根據這個算出leftsize
注意要判斷pstart == pend的情況;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode constructFromPrePost(int[] pre, int[] post) {
if(pre == null || pre.length == 0 || post == null || post.length == 0) {
return null;
}
return build(pre, 0, pre.length - 1, post, 0, post.length - 1);
}
private TreeNode build(int[] pre, int pstart, int pend,
int[] post, int ostart, int oend) {
if(pstart > pend || ostart > oend) {
return null;
}
if(pstart == pend) {
return new TreeNode(pre[pstart]);
}
TreeNode root = new TreeNode(pre[pstart]);
int j = ostart;
for(; j < oend; j++) {
if(post[j] == pre[pstart + 1]) {
break;
}
}
int leftsize = j - ostart + 1;
root.left = build(pre, pstart + 1, pstart + leftsize,
post, ostart, j);
root.right = build(pre, pstart + leftsize + 1, pend,
post, j + 1, oend -1);
return root;
}
}