Leetcode 106 Solution
This article provides solution to leetcode question 106 (construct-binary-tree-from-inorder-and-postorder-traversal)
Access this page by simply typing in "lcs 106" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal
Solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& postorder, int l1, int r1, vector<int>& inorder, int l2, int r2) {
if (l1 > r1 || l2 > r2)
return NULL;
int root_val = postorder[r1];
TreeNode* node = new TreeNode(root_val);
int pos = l2;
for (; pos < r2; pos++)
if (inorder[pos] == root_val)
break;
node->left = buildTree(postorder, l1, l1 + pos - l2 - 1, inorder, l2, pos - 1);
node->right = buildTree(postorder, l1 + pos - l2, r1 - 1, inorder, pos + 1, r2);
return node;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return buildTree(postorder, 0, postorder.size() - 1, inorder, 0, inorder.size() - 1);
}
};