题目描述:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Hide Tags Tree Array Depth-first Search
分析:
根据二叉树的中序和后序序列构造二叉树,和105题完全是类似的。只是根节点存在与后序序列的最后,然后分割出左子树序列和右子树序列,递归构造节点。
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Hide Tags Tree Array Depth-first Search
分析:
根据二叉树的中序和后序序列构造二叉树,和105题完全是类似的。只是根节点存在与后序序列的最后,然后分割出左子树序列和右子树序列,递归构造节点。
以下是C++实现代码,同样使用引用传参:
/**
* 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:
void buildHelp(TreeNode* &r,vector<int>& in,vector<int>& post,int inLef,int inRig,int postLef,int postRig)//根据后序和中序子序列构造节点
{
if(inLef > inRig) //表示空二叉树
r = NULL;
else
{
r = new TreeNode(post[postRig]); //利用后序序列的末元素生成根节点
int mid = inLef;
while(in[mid] != post[postRig]) //在中序序列中找到根节点对应的元素,将中序序列分割为左右两个中序子序列
mid++;
buildHelp(r->left,in,post,inLef,mid-1,postLef,postLef+mid-inLef-1); //利用左子序列的后序和中序构造左子树
buildHelp(r->right,in,post,1+mid,inRig,postLef+mid-inLef,postRig-1); //利用右子序列的后序和中序构造右子树
}
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int n = inorder.size();
if(n == 0)
return NULL;
TreeNode *r;
buildHelp(r,inorder,postorder,0,n-1,0,n-1); //调用辅助函数,构造二叉树
return r;
}
};