Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
遇到二叉树问题最先想到的是递归解决。使用 TreeNode * 引用,来保存临时结果
/**
* Definition for binary tree
* 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 *root=NULL;
if(inorder.empty()) return root;
sub(root,inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
return root;
}
void sub(TreeNode *&root,vector<int> &inorder,int istart,int iend,vector<int> &postorder,int pstart,int pend){
if(istart>iend||pstart>pend){
root=NULL;
return;
}
root=new TreeNode(postorder[pend]);
int split;
for(int i=istart;i<=iend;i++){
if(inorder[i]==postorder[pend]){
split=i;
}
}
int leftnum=split-istart; //表示左子树的节点个数
TreeNode *l,*r;
sub(l,inorder,istart,istart+leftnum-1,postorder,pstart,pstart+leftnum-1);
sub(r,inorder,istart+leftnum+1,iend,postorder,pstart+leftnum,pend-1);
root->left=l;
root->right=r;
}
};