/**
* 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) {
if(inorder.empty() || postorder.empty()) {
return NULL;
}
return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
}
TreeNode * buildTree(vector<int>& inorder, int iStart, int iEnd, vector<int>& postorder, int pStart, int pEnd) {
if(iStart > iEnd || pStart > pEnd) {
return NULL;
}
TreeNode * root = new TreeNode (postorder[pEnd]);
int i = iStart;
for(; i <= iEnd; ++i) {
if(inorder[i] == postorder[pEnd]) {
break;
}
}
root->left = buildTree(inorder, iStart, i - 1, postorder, pStart, pStart + i - iStart - 1);
root->right = buildTree(inorder, i + 1, iEnd, postorder, pEnd + i - iEnd, pEnd - 1);
return root;
}
};
4/21/2014
Leetcode -- Construct Binary Tree from Inorder and Postorder Traversal
Subscribe to:
Post Comments (Atom)
3 comments:
No words at all?
How do you get that alternative colors for each neighboring line? My code blocks are just grey all over.
There is a site called codeformatter, you can google it
Post a Comment