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.
» Solve this problemYou may assume that duplicates do not exist in the tree.
/** * 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&inorder, vector &postorder) { // Start typing your C/C++ solution below // DO NOT write int main() function int end = inorder.size() - 1; if (end < 0) return NULL; return getRoot(inorder, postorder, 0, end, postorder[end], 0); } TreeNode *getRoot(vector &inorder, vector &postorder, int start, int end, int rootVal, int offset) { if (start > end) return NULL; TreeNode *root = new TreeNode(rootVal); int rootPosInOrder = start; for (; rootPosInOrder < end; ++rootPosInOrder) { if (inorder[rootPosInOrder] == rootVal) break; } root->left = getRoot(inorder, postorder, start, rootPosInOrder - 1, postorder[rootPosInOrder - 1 + offset], offset); root->right = getRoot(inorder, postorder, rootPosInOrder + 1, end, postorder[end - 1 + offset], offset - 1); return root; } };
No comments:
Post a Comment