《剑指offer》重建二叉树

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

 
代码(c/c++):
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin) 
{
    
    int pre_len = pre.size();
    int in_len = vin.size();
    if(pre_len == 0 || in_len == 0 || pre_len != in_len)
        return NULL;
    TreeNode *head = new TreeNode(pre[0]);//创建根节点
    int root_ind = 0;//记录root在中序中的下标
    for(int i = 0; i<pre_len; i++){
        if(vin[i] == pre[0]){
            root_ind = i;
            break;
        }
    }
    vector<int> in_left, in_right,pre_left, pre_right;
    for(int j = 0; j<root_ind; j++){
        in_left.push_back(vin[j]);
        pre_left.push_back(pre[j+1]);//第一个为根根节点,跳过
    }
    for(int j = root_ind+1; j<pre_len; j++){
        in_right.push_back(vin[j]);
        pre_right.push_back(pre[j]);
    }
    //递归
    head->right = reConstructBinaryTree(pre_right, in_right);
    head->left = reConstructBinaryTree(pre_left, in_left);
    return head;
}
//中序遍历,可以查看是否重建成功
void inorderTraverseRecursive(TreeNode *root)
{
    if(root != NULL){
        inorderTraverseRecursive(root->left);
        cout<<root->val<<" ";
        inorderTraverseRecursive(root->right);
    }
}
int main(){
    int pre[] = {1,2,4,7,3,5,6,8};
    int in[] =  {4,7,2,1,5,3,8,6};
    vector<int> pre_vec(pre, pre+8);
    vector<int> in_vec(std::begin(in), std::end(in));
    // for(auto item: pre_vec)
    //     cout<<item<<' '<<endl;
    // for(auto item: in_vec)
    //     cout<<item<<' '<<endl;
    TreeNode *head ;
    head = reConstructBinaryTree(pre_vec, in_vec);
    inorderTraverseRecursive(head);
    return 0;
}

 

 
posted @ 2017-03-16 10:38  木白的菜园  阅读(1627)  评论(0编辑  收藏  举报