您的位置:首页 > 其它

LeetCode Construct Binary Tree from Inorder and Postorder Traversal

2012-11-15 19:55 501 查看
Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:

You may assume that duplicates do not exist in the tree.



Solution:

/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
typedef vector<int>::iterator vec_t;
void mybuild(TreeNode*& root,vec_t t1,vec_t t2,vec_t t3,vec_t t4){
if(t1==t2)
return;
root=new TreeNode(*(t4-1));
vec_t next=find(t1,t2,*(t4-1));
mybuild(root->left,t1,next,t3,t3+(next-t1));
mybuild(root->right,next+1,t2,t3+(next-t1),t4-1);
}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(inorder.empty())
return NULL;
TreeNode *head=NULL;
mybuild(head,inorder.begin(),inorder.end(),postorder.begin(),postorder.end());
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: