思路:记录好中序、后序在数组中的其实位置和当前元素个数,计算好左右子树根节点在数组中的位置和左右子树元素个数,只要左右子树的个数都为0,就会递归终止,返回叶子节点的指针,重复这一过程就是构造出了树结构。
code:
class Solution {
public:
TreeNode * buildTreePreInOrder(vector<int>::iterator preIt,vector<int>::iterator inIt, int num){
TreeNode * root = new TreeNode(*preIt);
vector<int>::iterator it = inIt;
while(*it != *preIt)
it++;
int numLeft = it - inIt, numRight = num - numLeft - 1;
if(numLeft > 0)
root->left = buildTreePreInOrder(preIt+1,inIt,numLeft);
if(numRight >0)
root->right = buildTreePreInOrder(preIt+numLeft+1,inIt+numLeft+1,numRight);
return root;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
TreeNode * root;
if(!preorder.empty())
root = buildTreePreInOrder(preorder.begin(),inorder.begin(),inorder.size());
else
return NULL;
return root;
}
};