根据前序序列和中序序列重建二叉树

本文详细解析了如何利用前序遍历和中序遍历序列重构二叉树的过程,通过递归方法找到根节点,划分左右子树,最终实现树的重建。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章目录

题目

已知:
前序 1,2,4,7,3,5,6,8
中序 4,7,2,1,5,3,8,6

要求:
重新构建一颗二叉树

解答

因为前序的第一个就是根节点,所以先找到根节点在中序中的位置
在这里插入图片描述

求出左子树的长度,确定左子树在前序和中序中的范围,以及右子树在前序和中序中的范围

在这里插入图片描述

求出两个序列中,左子树的范围和右子树的范围
在这里插入图片描述

class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        return pre_order(0, vin.size() - 1, 0, vin.size() - 1, pre, vin);
    }

    TreeNode *pre_order(int leftpre, int rightpre, int leftin, int rightin, vector<int> &pre, vector<int> &in) {
        if (leftpre > rightpre || leftin > rightin)
            return NULL;
        TreeNode *root = new TreeNode(pre[leftpre]);
        int rootin = leftin;
        while (rootin <= rightin && pre[leftpre] != in[rootin])
            rootin++;
        int left = rootin - leftin;
        root->left = pre_order(leftpre + 1, leftpre + left, leftin, rootin - 1, pre, in);
        root->right = pre_order(leftpre + left + 1, rightpre, rootin + 1, rightin, pre, in);
        return root;
    }
};
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        def helper(left_pre, right_pre, left_in, right_in, preorder, inorder):
            if left_pre > right_pre or left_in > right_in:
                return
            # 确定根节点
            root = TreeNode(preorder[left_pre])
            root_in = left_in
            # 找到根节点在中序中的位置
            while root_in <= right_in and preorder[left_pre] != inorder[root_in]:
                root_in += 1
            # 求出左子树的长度
            left_tree_length = root_in - left_in
            # 确定左子树在前序和中序中的范围
            root.left = helper(left_pre + 1, left_pre + left_tree_length, left_in, root_in - 1, preorder, inorder)
            # 确定右子树在前序和中序中的范围
            root.right = helper(left_pre + left_tree_length + 1, right_pre, root_in + 1, right_in, preorder, inorder)
            return root
        
        
        return helper(0, len(preorder) - 1, 0, len(inorder) - 1, preorder, inorder)

参考:
重建二叉树

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值