您的位置:首页 > 其它

LeetCode "Construct Binary Tree from Inorder and Postorder Traversal"

2014-07-23 04:13 344 查看
Another textbook problem. We take back of postorder array as the current root, and then we can split the inorder array: 1st half for current right child, and 2nd for current left.

class Solution {
public:
TreeNode *_buildTree(int in[], int i0, int i1, int insize, int post[], int &inx_p)
{
if(inx_p < 0 || i0 > i1) return NULL;

TreeNode *pRoot = new TreeNode(post[inx_p]);

int iRoot = std::find(in, in + insize, post[inx_p--]) - in;
TreeNode *pRight = _buildTree(in, iRoot + 1, i1, insize, post, inx_p);
pRoot->right = pRight;
TreeNode *pLeft= _buildTree(in, i0, iRoot-1, insize, post, inx_p);
pRoot->left = pLeft;
return pRoot;
}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
int *in = new int[inorder.size()];
std::copy(inorder.begin(), inorder.end(), in);
int *post = new int[postorder.size()];
std::copy(postorder.begin(), postorder.end(), post);
int inx = postorder.size() - 1;
return _buildTree(in, 0, inorder.size()-1, inorder.size(), post, inx);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: