zoukankan      html  css  js  c++  java
  • 《剑指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;
    }
     
  • 相关阅读:
    新机自动创建yum库
    一段自动添加证书命令
    一段托盘程序
    date
    1234567890 转换成 1,234,567,890
    删除localStorage数组中其中一个元素(根据元素中的属性key)
    xcode6 ios launchimage
    画分割线
    裁剪和打水印
    UITextView添加一个placeholder功能
  • 原文地址:https://www.cnblogs.com/mooba/p/6558201.html
Copyright © 2011-2022 走看看