题解 | #从中序与后序遍历序列构造二叉树#
从中序与后序遍历序列构造二叉树
http://www.nowcoder.com/practice/ab8dde7f01f3440fbbb7993d2411a46b
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param inorder int整型vector 中序遍历序列
* @param postorder int整型vector 后序遍历序列
* @return TreeNode类
*/
void BuildNode(TreeNode *& root,vector<int> inorder, vector<int> postorder,int l1,int r1,int l2,int r2){
if(r1 < l1 || r2 < l2)
return ;
if(root == NULL){
root = new TreeNode(postorder[r2]);
root->left = NULL;
root->right = NULL;
}
int pos = find(inorder.begin(),inorder.end(),postorder[r2]) - inorder.begin();
BuildNode(root->right, inorder, postorder,pos + 1,r1,r2 - (r1 - pos),r2 - 1);
BuildNode(root->left, inorder, postorder,l1,pos - 1,l2,r2 - (r1 - pos) - 1);
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
// write code here
TreeNode* root = NULL;
BuildNode(root, inorder, postorder, 0, inorder.size() - 1, 0,postorder.size() - 1);
return root;
}
};