Given inorder and postorder traversal of a tree, construct the binary tree
1:中序和后序遍历构成一棵树。2:採用递归的方法。3:把两个数组分别分成两部分;4:注意递归结束情况
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
{
if(inorder.size() == 0 || postorder.size() == 0 || inorder.size() != postorder.size())
{
return NULL;
}
int size = (int)inorder.size();
return buildTreeCore(inorder, 0, postorder, 0, size);
}
TreeNode *buildTreeCore(vector<int> &inorder, int inStart, vector<int> &postorder, int postStart, int length)
{
if(length == 1)
{
if(inorder[inStart] != postorder[postStart])
{
return NULL;
}
}
int rootValue = postorder[postStart + length - 1];
TreeNode *root = new TreeNode(rootValue);
int i = 0;
for(; i < length; i++)
{
if(inorder[inStart + i] == rootValue)
{
break;
}
}
if(i == length)
{
return NULL;
}
if(i > 0)
{
root->left = buildTreeCore(inorder, inStart, postorder, postStart, i);
}
if(i < length - 1)
{
root->right = buildTreeCore(inorder, inStart + i + 1, postorder, postStart + i, length - i - 1);
}
return root;
}