题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */10 class Solution {11 public:12 struct TreeNode* reConstructBinaryTree(vector pre,vector in) {13 if (pre.size() != 0 && in.size() != 0 && pre.size() == in.size())14 {15 return build(pre,in,0,pre.size()-1,0,in.size()-1);16 }17 else18 {19 return NULL;20 }21 22 }23 24 struct TreeNode* build(vector pre,vector in,int l1,int r1,int l2,int r2)25 {26 if(l1<=r1)27 {28 int i=l2;29 while(pre[l1]!=in[i])30 i++;31 TreeNode* T= new TreeNode(in[i]);32 T->left=build(pre,in,l1+1,l1+i-l2,l2,i-1);33 T->right=build(pre,in,l1+i-l2+1,r1,i+1,r2);34 return T;35 }36 else return NULL;37 }38 };