889. Construct Binary Tree from Preorder and Postorder Traversal

在这里插入图片描述

/**
 * 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;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值