剑指offer:重建二叉树

来源:互联网 发布:单片机modbus rtu程序 编辑:程序博客网 时间:2024/06/05 18:43

题目描述

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

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) {        if(pre.size()!=in.size()){            return NULL;        }        if(pre.size()==0){            return NULL;        }        return helper(pre,0,pre.size()-1,in,0,in.size()-1);    }private:    TreeNode* helper(vector<int> &pre,int preL,int preR,vector<int> &in,int inL,int inR){     //   if(preL<=preR && inL<=inR){            TreeNode* root=new TreeNode(pre[preL]);            int mid=inL;            while(in[mid]!=pre[preL]) mid++;            int cnt=mid-inL;            if(inL==mid){                root->left=NULL;            }else{                root->left=helper(pre,preL+1,preL+cnt,in,inL,mid-1);            }            if(inR==mid){                root->right=NULL;            }else{                root->right=helper(pre,preL+cnt+1,preR,in,mid+1,inR);            }            return root;      //  }    }};

注意左右子树为null时的判断!!

0 0
原创粉丝点击