与上一题思路一样,递归,划分数组
但前序不能单纯的一【0】来判断根节点
class Solution {
public:
TreeNode* traversal (vector<int>& inorder, int inorderBegin, int inorderEnd, vector<int>& preorder, int preorderBegin, int preorderEnd) {
if(preorderBegin==preorderEnd)return NULL;
//前序第一个值为根节点
int rootvalue=preorder[preorderBegin];
TreeNode* root =new TreeNode(rootvalue);
//叶子节点
if(preorderEnd-preorderBegin==1)return root;
//找到中序遍历的切割点
int delimiterindex;
for(delimiterindex=inorderBegin;delimiterindex<inorderEnd;delimiterindex++)
{
if(inorder[delimiterindex]==rootvalue)break;
}
//切割中序数组
//中序左区间
int leftinorderbegin=inorderBegin;
int leftinorderend=delimiterindex;
//中序右区间
int rightinorderbegin=delimiterindex+1;
int rightinorderend=inorderEnd;
//切割前序数组
//前序左区间
int leftpreorderbegin=preorderBegin+1;
int leftpreorderend=preorderBegin+1+delimiterindex-inorderBegin;
//前序右区间
int rightpreorderbegin=preorderBegin+1+delimiterindex-inorderBegin;
int rightpreorderend=preorderEnd;
root->left = traversal(inorder, leftinorderbegin, leftinorderend, preorder, leftpreorderbegin, leftpreorderend);
root->right = traversal(inorder, rightinorderbegin, rightinorderend, preorder, rightpreorderbegin, rightpreorderend);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if(inorder.size()==0||preorder.size()==0) return NULL;
return traversal(inorder,0,inorder.size(),preorder,0,preorder.size());
}