剑指offer面试题7:重建二叉树

1.从前序与中序遍历序列构造二叉树

在这里插入图片描述

1.1 解题思路

前序序列的第一个节点为根节点。 中序序列的根节点的值在中间,并且左侧为其左子树,右侧为其右子树。

重建算法思路很清晰,先确定根节点,然后从中序序列中找到根节点的左子树和右子树;随后递归重建其左子树和右子树即可。
1)在中序序列中寻找根节点的编号,根据编号是否位于序列两端判断是否存在左右子树,并重建。
2)根据两个序列,重建某棵二叉树

1.2 code

//
// Created by wbzhang on 2020/6/29.
//
#include <vector>

using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

TreeNode* constructTree(vector<int> preorder,vector<int> inorder){
    if(preorder.size()*inorder.size()==0){
        return NULL;
    }
    // 1.根节点的值
    int rootValue = preorder[0];
    TreeNode* root = new TreeNode(rootValue);
    root->left = root->right = NULL;
    // 2.从中序遍历序列中寻找根节点的值
    int inRootInd = 0;
    for(int i=0;i<inorder.size();++i){
        if(inorder[i]==rootValue){
            inRootInd = i;
        }
    }

    // 然后分别根据某一段来重建左子树和右子树,再将其连接到根节点即可
    // int leftLength = inRootInd;
    if(inRootInd!=0){
        vector<int> leftPreVec(preorder.begin()+1,preorder.begin()+inRootInd+1);
        vector<int> leftInVec(inorder.begin(),inorder.begin()+inRootInd);
        root->left = constructTree(leftPreVec,leftInVec);
    }else root->left = NULL;

    if(inRootInd != inorder.size()-1){
        vector<int> rightPreVec(preorder.begin()+inRootInd+1,preorder.end());
        vector<int> rightInVec(inorder.begin()+inRootInd+1,inorder.end());
        root->right = constructTree(rightPreVec,rightInVec);
    }else root->right = NULL;

    return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
    if(preorder.size()*inorder.size()==0 ) return NULL;
    return constructTree(preorder,inorder);
}

int main(){
    vector<int> preorder={3,9,20,15,7};
    vector<int> inorder={9,3,15,20,7};
    TreeNode* root = buildTree(preorder,inorder);

    return 0;
}

扩展:从中序和后续遍历序列重建二叉树

中序序列的特点与上面描述相同。 后序遍历序列的特点在于根节点在序列最后面,则重建思路与之相同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值