/**
* 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.length == 0){
return null;
}else{
return constructFromPrePostCore(pre, post, 0, pre.length - 1, 0, post.length - 1);
}
}
public TreeNode constructFromPrePostCore(int[] pre, int[] post, int l_pre, int r_pre, int l_post, int r_post) {
if(l_pre == r_pre){
TreeNode cur_Node = new TreeNode(pre[l_pre]);
return cur_Node;
}else{
TreeNode cur_Node = new TreeNode(pre[l_pre]);
int mid_pre_val = post[r_post - 1];
int mid_post_val = pre[l_pre + 1];
int index_mid_pre_val = 0;
int index_mid_post_val = 0;
for(int i = l_pre; i <= r_pre; ++i){
if(pre[i] == mid_pre_val){
index_mid_pre_val = i;
break;
}
}
for(int i = l_post; i <= r_post; ++i){
if(post[i] == mid_post_val){
index_mid_post_val = i;
break;
}
}
if((l_pre + 1) == index_mid_pre_val){
cur_Node.left = constructFromPrePostCore(pre, post, l_pre + 1, r_pre, l_post, r_post - 1);
}else{
cur_Node.left = constructFromPrePostCore(pre, post, (l_pre + 1), (index_mid_pre_val - 1), (l_post), (index_mid_post_val));
cur_Node.right = constructFromPrePostCore(pre, post, (index_mid_pre_val), (r_pre), (index_mid_post_val + 1), (r_post - 1));
}
return cur_Node;
}
}
}
889. Construct Binary Tree from Preorder and Postorder Traversal
最新推荐文章于 2020-03-01 11:14:51 发布