题目:
Given inorder and postorder traversal of a tree, construct the binary tree.
跟之前的通过先序遍历和中序遍历构建二叉树一样,有个区别是,这次的根结点每次都从后序列表中从后向前扫。代码:
1 TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { 2 // IMPORTANT: Please reset any member data you declared, as 3 // the same Solution instance will be reused for each test case. 4 int idx=postorder.size()-1; 5 return buildTree(inorder,postorder,0,inorder.size(),&idx); 6 } 7 TreeNode *buildTree(vector<int> &inorder,vector<int> &postorder,int start,int len,int* idx){ 8 if(!len || idx<0) return NULL; 9 TreeNode* root=(TreeNode*)malloc(sizeof(TreeNode)); 10 root->val=postorder[*idx]; 11 root->left=NULL; 12 root->right=NULL; 13 int i=start; 14 while(i-start<len){ 15 if(inorder[i]==root->val) break; 16 i++; 17 } 18 19 if(i-start+1<len){ 20 root->right=buildTree(inorder,postorder,i+1,start+len-i-1,&(--*idx)); 21 } 22 if(i>start){ 23 root->left=buildTree(inorder,postorder,start,i-start,&(--*idx)); 24 } 25 return root; 26 }