注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
/**
* 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) {
int size = inorder.size();
TreeNode *root = nullptr;
root = find_root(inorder,postorder);
return root;
}
TreeNode *find_root(vector<int> inorder , vector<int>postorder)
{
TreeNode *leftNode = nullptr;
TreeNode *rightNode = nullptr;
int i =0;
TreeNode *rootNode = new TreeNode(1);
vector<int> preNxtInorder;
vector<int> hinNxtInorder;
vector<int> preNxtPostorder;
vector<int> hinNxtPostorder;
int rootVal = -1;
if(inorder.size()>1)
{
rootVal = postorder.back();
rootNode->val = rootVal;
cout<<"find root = "<<rootVal<<endl;
for(i=0;i<inorder.size();i++)
{
if(rootVal == inorder.at(i))
{
break;
}
}
cout<<i<<endl;
for(int j=0;j<i;j++)
{
preNxtInorder.push_back(inorder.at(j));
preNxtPostorder.push_back(postorder.at(j));
cout<<"prepush"<<"inorder = "<<preNxtInorder.back()<<"postorder = "<<preNxtPostorder.back()<<endl;
}
for(int j=i+1;j<inorder.size();j++)
{
hinNxtInorder.push_back(inorder.at(j));
hinNxtPostorder.push_back(postorder.at(j-i-1+preNxtPostorder.size()));
cout<<"hinpush"<<"inorder = "<<hinNxtInorder.back()<<"postorder = "<<hinNxtPostorder.back()<<endl;
}
leftNode = find_root(preNxtInorder , preNxtPostorder);
rightNode = find_root(hinNxtInorder , hinNxtPostorder);
rootNode->left = leftNode;
rootNode->right = rightNode;
}
else
{
rootNode->val = postorder.front();
cout<<"finish push =" <<rootNode->val<<endl;
rootNode->left = nullptr;
rootNode->right = nullptr;
}
return rootNode;
}
};