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

题目描述

重建二叉树

算法分析

要注意前序遍历和中序遍历的特点,利用递归的思想实现
剑指Offer——面试题7:重建二叉树_第1张图片

程序代码

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) 
    {
        vector<int> preleft;//左子树前序遍历
        vector<int> preright;//右子树前序遍历
        vector<int> Inleft;//左子树中序遍历
        vector<int> Inright;//右子树中序遍历
        int root_data = pre[0];
        int index = 0;
        // 构建左右子树的前序和中序遍历
        while(vin[index] != root_data)
        {
            Inleft.push_back(vin[index]);
            preleft.push_back(pre[1+index]);
            index++;
        }
        index++;
        while(index != vin.size())
        {
            Inright.push_back(vin[index]);
            preright.push_back(pre[index]);
            index++;
        }
        //递归解决
        TreeNode *root = new TreeNode(root_data);
        if(!preleft.empty()) root->left = reConstructBinaryTree(preleft,Inleft);
        else root->left = nullptr;
        if(!preright.empty()) root->right = reConstructBinaryTree(preright,Inright);
        else root->right = nullptr;
        return root;
        
    }
};

你可能感兴趣的:(数据结构与算法)