leetcode--Construct Binary Tree from Inorder and Postorder Traversal
1.题目描述
Given inorder and postorder traversal of a tree, construct the binary tree.Note:You may assume that duplicates do not exist in the tree.
2.解法分析
理解了什么是后序,什么是中序,此题迎刃而解,需要注意的是,解此题需要数组中没有相同的元素,不然的话可能性就多了。
/**
* 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) {// Start typing your C/C++ solution below
// DO NOT write int main() function
if(inorder.size()!=postorder.size()||inorder.size()==0)return NULL;return myBuildTree(inorder,postorder,0,inorder.size()-1,0,postorder.size()-1);
}TreeNode *myBuildTree(vector<int> &inorder, vector<int> &postorder,int iStart,int iEnd,int pStart,int pEnd){if(iStart>iEnd)return NULL;TreeNode *parent = new TreeNode(postorder[pEnd]);
int rootIndex = iStart;
while(inorder[rootIndex]!=postorder[pEnd]){rootIndex++;}
parent->left = myBuildTree(inorder,postorder,iStart,rootIndex-1,pStart,pStart+rootIndex-iStart-1);parent->right = myBuildTree(inorder,postorder,rootIndex+1,iEnd,pEnd-(iEnd-rootIndex),pEnd-1);return parent;
}};