Leetcode 105 Solution

This article provides solution to leetcode question 105 (construct-binary-tree-from-preorder-and-inorder-traversal)

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-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>& preorder, int l1, int r1, vector<int>& inorder, int l2, int r2) { if (l1 > r1 || l2 > r2) return NULL;
int root_val = preorder[l1]; TreeNode* node = new TreeNode(root_val);
int pos = l2; for (; pos <= r2; pos++) if (inorder[pos] == root_val) break;
node->left = buildTree(preorder, l1 + 1, l1 + 1 + pos - l2 - 1, inorder, l2, pos - 1); node->right = buildTree(preorder, l1 + 1 + pos - l2, r1, inorder, pos + 1, r2);
return node; }
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { return buildTree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1); } };