中序遍历和后序遍历树构造二叉树
根据中序遍历和后序遍历树构造二叉树
注意事项
你可以假设树中不存在相同数值的节点
样例
给出树的中序遍历: [1,2,3] 和后序遍历: [1,3,2]
返回如下的树:
2
/
1 3标签
二叉树
code
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
/**
*@param inorder : A list of integers that inorder traversal of a tree
*@param postorder : A list of integers that postorder traversal of a tree
*@return : Root of a tree
*/
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
// write your code here
TreeNode *root = NULL;
vector<int> inorder_l,inorder_r,postorder_l,postorder_r;
int i,root_index=0;
int size = postorder.size();
if(inorder.empty()!=1 || postorder.empty()!=1) {
root = new TreeNode(postorder[size-1]); // 在后序队列中找根节点
// 在中序队列中找出根节点位置
for(i=0; i<inorder.size(); i++) {
if(postorder[size-1] == inorder[i])
break;
root_index++;
}
// 左右子树的前序、中序队列
for(i=0; i<root_index; i++) {
postorder_l.push_back(postorder[i]);
inorder_l.push_back(inorder[i]);
}
for(i=root_index+1; i<inorder.size(); i++) {
postorder_r.push_back(postorder[i-1]);
inorder_r.push_back(inorder[i]);
}
root->left = buildTree(inorder_l, postorder_l);
root->right = buildTree(inorder_r, postorder_r);
}
return root;
}
};