-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConstructBinaryTreefromPreorderandInorderTraversal_105.cpp
52 lines (41 loc) · 1.58 KB
/
ConstructBinaryTreefromPreorderandInorderTraversal_105.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
~ Author : leetcode.com/tridib_2003/
~ Problem : 105. Construct Binary Tree from Preorder and Inorder Traversal
~ Link : https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
*/
/**
* 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:
int preIdx = 0;
int searchNode(vector<int> inorder, int startIdx, int endIdx, int value) {
for (int i = startIdx; i <= endIdx; ++i)
if (inorder[i] == value)
return i;
return -1;
}
TreeNode* buildingTree(vector<int> preorder, vector<int> inorder, int startIdx, int endIdx) {
if (startIdx > endIdx)
return NULL;
TreeNode *newNode = new TreeNode(preorder[preIdx]);
++preIdx;
if (startIdx == endIdx)
return newNode;
int inPos = searchNode(inorder, startIdx, endIdx, newNode -> val);
newNode -> left = buildingTree(preorder, inorder, startIdx, inPos - 1);
newNode -> right = buildingTree(preorder, inorder, inPos + 1, endIdx);
return newNode;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return buildingTree(preorder, inorder, 0, preorder.size() - 1);
}
};