FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-interview-patterns/cpp/Trees/build_binary_tree.cpp at main · ByteByteGoHq/coding-interview-patterns · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
ByteByteGoHq
/
coding-interview-patterns
Public
Notifications
You must be signed in to change notification settings
Fork
303
Star
1.3k
Code
Issues
0
Pull requests
5
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-interview-patterns
/
cpp
/
Trees
/
build_binary_tree.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
47 lines (44 loc) · 1.79 KB
Breadcrumbs
coding-interview-patterns
/
cpp
/
Trees
/
build_binary_tree.cpp
Copy path
File metadata and controls
47 lines (44 loc) · 1.79 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
#
include
<
vector
>
#
include
<
unordered_map
>
#
include
"
ds/TreeNode.h
"
using
ds::TreeNode;
/*
*
* Definition of TreeNode:
* struct TreeNode {
* int val;
* TreeNode* left;
* TreeNode* right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
* };
*/
TreeNode*
buildBinaryTree
(std::vector<
int
>& preorder, std::vector<
int
>& inorder) {
//
Populate the hash map with the inorder values and their indexes.
std::unordered_map<
int
,
int
> inorderIndexesMap;
for
(
int
i =
0
; i < inorder.
size
(); i++) {
inorderIndexesMap[inorder[i]] = i;
}
//
Build the tree and return its root node.
int
preorderIndex =
0
;
return
buildSubtree
(
0
, inorder.
size
() -
1
, preorder, inorder, preorderIndex, inorderIndexesMap);
}
TreeNode*
buildSubtree
(
int
left,
int
right, std::vector<
int
>& preorder, std::vector<
int
>& inorder,
int
& preorderIndex, std::unordered_map<
int
,
int
>& inorderIndexesMap) {
//
Base case: if no elements are in this range, return nullptr.
if
(left > right) {
return
nullptr
;
}
int
val = preorder[preorderIndex];
//
Set 'inorder_index' to the index of the same value pointed at by
//
'preorder_index'.
int
inorderIndex = inorderIndexesMap[val];
TreeNode* node =
new
TreeNode
(val);
//
Advance 'preorder_index' so it points to the value of the next
//
node to be created.
preorderIndex++;
//
Build the left and right subtrees and connect them to the current
//
node.
node->
left
=
buildSubtree
(left, inorderIndex -
1
, preorder, inorder, preorderIndex, inorderIndexesMap);
node->
right
=
buildSubtree
(inorderIndex +
1
, right, preorder, inorder, preorderIndex, inorderIndexesMap);
return
node;
}
Back
|
FazBrowse Home
|
New Git URL