剑指offer第四题:重建二叉树(c++实现)

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

一个小Tips:
查询元素在vector中位置可以用vector::iterator iter=find(v.begin(),v.end(),num)函数和distance(v.begin(),iter)函数

#include  
#include  
#include 
#include 
  
using namespace std; 

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* reConstructBinaryTree(vector pre,vector vin) {
    if(pre.empty()||vin.empty())
    {
        return NULL; 
    }

    int root = pre.at(0);
    TreeNode* result=new TreeNode(root);


    vector::iterator iter = find(vin.begin(),vin.end(),root);
    int ltN = distance(vin.begin(),iter);

    vector pre_lft,pre_rgt;
    vector vin_lft,vin_rgt;
    for(int i=0;ileft=reConstructBinaryTree(pre_lft,vin_lft);
    result->right=reConstructBinaryTree(pre_rgt,vin_rgt);

    return result;
}
vector preOrder(TreeNode* tree)
{
    vector preOderV;
    if(tree == NULL)
    {
        return preOderV;
    }
    stack tmpStack;
    while(tree != NULL || !tmpStack.empty())
    {
        if(tree!=NULL)
        {
            preOderV.push_back(tree->val);
            tmpStack.push(tree);
            tree=tree->left;
        }
        else
        {
            tree=tmpStack.top();
            tmpStack.pop();
            tree=tree->right;
        }
        
    }
    return preOderV;
}
int main() 
{  
    vector pre={1,2,4,7,3,5,6,8};
    vector vin={4,7,2,1,5,3,8,6};  
    TreeNode* recTree = reConstructBinaryTree(pre,vin);
    vector result = preOrder(recTree);
    for(auto i : result)
    {
        cout<

具体思路可以参考以下文章:

剑指Offer面试题:5.重建二叉树

[剑指offer] 重建二叉树

你可能感兴趣的:(C++,算法)