LeetCode 889. Construct Binary Tree from Preorder and Postorder Traversal(Medium)

Description:
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]

Note:

  • 1 <= pre.length == post.length <= 30
  • pre[] and post[] are both permutations of 1, 2, …, pre.length.
  • It is guaranteed an answer exists. If there exists multiple answers, you can return any of them.

Analysis:
The key point of the problem is to figure out the intervals of indexes of left subtree and right subtree in pre  and post respectively. Here we use L to denote the number of nodes in the left subtree. Then we can get the following graph:
在这里插入图片描述

As the following graph show, traverse the post  until an element that is equal to pre[1]is found, this element represents the root node of the left subtree in post, then we can obtain the value of L. We can use a recursion to apply this strategy to construct the root node, left subtree and right subtree.


Code:

/**
 * 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 if(pre.length == 1) {
            return new TreeNode(pre[0]);
        }else{
            TreeNode root = new TreeNode(pre[0]);
            
            int N = pre.length;
            int L = 0;
            for(int i = 0; i < N; i++) {
                L += 1;
                if(post[i] == pre[1]) {
                    break;
                }
            }
            
            root.left = constructFromPrePost(Arrays.copyOfRange(pre, 1, L+1), Arrays.copyOfRange(post, 0, L));
            root.right = constructFromPrePost(Arrays.copyOfRange(pre, L+1, N), Arrays.copyOfRange(post, L, N-1));
            
            return root;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值