Sword point offer (4)

Topic Description
Input the results of preorder traversal and inorder traversal of a binary tree, please reconstruct the binary tree. It is assumed that the results of the input preorder traversal and inorder traversal do not contain duplicate numbers. For example, input the preorder traversal sequence {1,2,4,7,3,5,6,8} and the inorder traversal sequence {4,7,2,1,5,3,8,6}, then rebuild the binary tree and return.

Time limit: 1 second Space limit: 32768K Heat index: 335630

Idea: Use recursion

#include<iostream>
#include<vector>
#include<stack>
#include<stdio.h>
#include<stdlib.h>
#include<string>

 using namespace std;

//Definetion 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){
        if(vin.size()==0)//递归回到头条件
        //if(pre.size()==0)//if(pre.empty())//if(in.empty())
            return NULL;

        vector<int> in_left,in_right,pre_left,pre_right;
        int cur=pre[0];//前序遍历的第一个结点就是根结点
        TreeNode* root=new TreeNode(cur);
        int p=0;

        for(;p<vin.size();p++){
            if(vin[p]==cur)    //p记录根节点在中序遍历中的位置
                break;
        }

        for(int i=0;i<vin.size();i++){
            if(i<p){
                in_left.push_back(vin[i]);
                pre_left.push_back(pre[i+1]);
            }
            else if(i>p){
                in_right.push_back(vin[i]);
                pre_right.push_back(pre[i]);

            }
        }

        root->left=reConstructBinaryTree(pre_left,in_left);
        root->right=reConstructBinaryTree(pre_right,in_right);
        return root;
    }   


void preOrder(TreeNode* &T){
    if(T==NULL) return;
    else{
        cout<<T->val<<" ";
        preOrder(T->left);
        preOrder(T->right);
    }
}

};

int main(){
    solution s;
    TreeNode* T;

    int a[8]={1,2,4,7,3,5,6,8};
    vector<int> pre(&a[0],&a[8]);
    int b[8]={4,7,2,1,5,3,8,6};
    vector<int> in(&b[0],&b[8]);

    T=s.reConstructBinaryTree(pre,in);
    cout<<"创建成功!"<<endl;

    cout<<"前序遍历结果:"<<endl;
    s.preOrder(T);

    return 0;
}

Reference blog: https://blog.csdn.net/u013686654/article/details/73729288

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325688042&siteId=291194637