Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
根据中序和后序遍历确定一个二叉树,一开始打算每一个都用vector储存,结果内存超限了。
内存超限代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
TreeNode *head = getBinaryTree(inorder, postorder);
return head;
}
TreeNode *getBinaryTree(vector<int>& inorder, vector<int>& postorder)
{
if(inorder.size() == 0) return NULL;
vector<int>::iterator it = postorder.end() - 1;
TreeNode *head = new TreeNode(*it);
if(postorder.size() == 1)
{
return head;
}
else
{
vector<int>::iterator center = find(inorder.begin(), inorder.end(),head->val);
vector<int> left_inorder;
for(vector<int>::iterator temp = inorder.begin();temp < center;temp++)
{
left_inorder.push_back(*temp);
}
vector<int> left_post;
int i = 0;
for(;i<left_inorder.size();i++)
{
left_post.push_back(postorder[i]);
}
head->left = getBinaryTree(left_inorder, left_post);
vector<int> right_inorder;
vector<int> right_post;
for(vector<int>::iterator temp = center+1;temp<inorder.end();temp++)
{
right_inorder.push_back(*temp);
}
for(int j = 0;j<right_inorder.size();j++,i++)
{
right_post.push_back(postorder[i]);
}
head->right = getBinaryTree(right_inorder, right_post);
return head;
}
}
};
后来上网上查看了一下题解发现不用那么麻烦,直接在原向量上操作即可。看了思路之后还是错了好几次,主要原因就是边界的确定。
AC代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return getBinaryTree(inorder, 0, inorder.size() -1, postorder, 0, inorder.size()-1);
}
TreeNode *getBinaryTree(vector<int>& inorder,int begin1, int end1, vector<int>& postorder, int begin2, int end2)
{
if(begin1 > end1)
return NULL;
else if(begin1 == end1)
return new TreeNode(inorder[begin1]);
TreeNode *head = new TreeNode(postorder[end2]);
int i = begin1;
for(i;i<=end1;i++)
{
if(inorder[i] == postorder[end2]) break;
}
int leftlen = i - begin1;
head->left = getBinaryTree(inorder, begin1, begin1+leftlen - 1, postorder, begin2, begin2 + leftlen -1);//注意边界
head->right = getBinaryTree(inorder, begin1+leftlen+1, end1, postorder, begin2+leftlen, end2 - 1);//注意边界
return head;
}
};
解体的关键就是求出中序遍历中根结点的位置和左子树的长度。下次再做一个前序和中序遍历的题再练练这种思路。