-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathConstruct Binary Tree from Preorder and Inorder Traversal.cpp
62 lines (48 loc) · 1.6 KB
/
Construct Binary Tree from Preorder and Inorder Traversal.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
53
54
55
56
57
58
59
60
61
62
/*
Solution by Rahul Surana
***********************************************************
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.
***********************************************************
*/
#include <bits/stdc++.h>
/**
* 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* build(vector<int> preorder, vector<int> inorder,int& i,int s,int e){
if(s>e){
i--;
return NULL;
}
if(s==e){
return new TreeNode(preorder[i]);
}
int ind = -1;
for(int j = s; j <= e; j++){
if(preorder[i] == inorder[j]){
ind = j;
break;
}
}
TreeNode* root = new TreeNode(preorder[i]);
i++;
root -> left = build(preorder,inorder,i,s,ind-1);
i++;
root -> right = build(preorder,inorder,i,ind+1,e);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int i = 0;
return build(preorder,inorder,i,0,preorder.size()-1);
}
};