[LeetCode] Construct Binary Tree from Preorder and Inorder Traversal

105. Construct Binary Tree from Preorder and Inorder Traversal

Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& p, vector<int>& i) {
if(p.empty()) return nullptr;
int rootPos = distance(i.begin(), find(i.begin(), i.end(), p[0]));
vector<int> pl(p.begin() + 1, p.begin() + 1 + rootPos), pr(p.begin() + 1 + rootPos, p.end()), il(i.begin(), i.begin() + rootPos), ir(i.begin() + rootPos + 1, i.end());
return new TreeNode(p[0], buildTree(pl, il), buildTree(pr, ir));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/19/PS/LeetCode/construct-binary-tree-from-preorder-and-inorder-traversal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.