LeetCode230215_147、889. 根据前序和后序遍历构造二叉树

给定两个整数数组,preorder 和 postorder ,其中 preorder 是一个具有 无重复 值的二叉树的前序遍历,postorder 是同一棵树的后序遍历,重构并返回二叉树。

如果存在多个答案,您可以返回其中 任何 一个。

图1 根据前序遍历和后续遍历构造二叉树

示例 1:

输入:preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]
输出:[1,2,3,4,5,6,7]

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-postorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解、递归解法,首先根据前序遍历的第一个节点是当前树的根节点,后一个节点为左子树的根节点,然后在后序遍历中进行索引查找,找到对应值的索引+1即为左子树的节点个数,创建前序遍历左子树的数组、前序遍历右子树的数组、后序遍历左子树的数组、后序遍历右子树的数组,进行节点递归生成。

class Solution {
    public TreeNode constructFromPrePost(int[] pre, int[] post) {
        if (pre == null || pre.length == 0) return null;
        return dfs(pre, post);
    }
    public TreeNode dfs(int[] pre, int[] post) {
        if (pre == null || pre.length == 0) return null;
        int n = pre.length;
        if (n == 1) return new TreeNode(pre[0]);
        TreeNode root = new TreeNode(pre[0]);
        for (int i = 0; i < post.length; i++) {
            if (pre[1] == post[i]) {
                int leftCount = i + 1;
                int[] pre_left = Arrays.copyOfRange(pre, 1, leftCount + 1);
                int[] pre_right = Arrays.copyOfRange(pre, leftCount + 1, n);
                int[] post_left = Arrays.copyOfRange(post, 0, leftCount);
                int[] post_right = Arrays.copyOfRange(post, leftCount, n -1);
                root.left = dfs(pre_left, post_left);
                root.right = dfs(pre_right, post_right);
                break;
            }
        }
        return root;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值