FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-interview-patterns/java/Trees/BuildBinaryTree.java at main · iamthatdev/coding-interview-patterns · GitHub
iamthatdev
/
coding-interview-patterns
Public
forked from
ByteByteGoHq/coding-interview-patterns
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-interview-patterns
/
java
/
Trees
/
BuildBinaryTree.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
50 lines (45 loc) · 1.64 KB
Breadcrumbs
coding-interview-patterns
/
java
/
Trees
/
BuildBinaryTree.java
Copy path
File metadata and controls
50 lines (45 loc) · 1.64 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
48
49
50
import
java
.
util
.
HashMap
;
import
java
.
util
.
Map
;
import
DS
.
TreeNode
;
/*
// Definition of TreeNode:
class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
*/
public
class
BuildBinaryTree
{
int
preorderIndex
=
0
;
Map
<
Integer
,
Integer
>
inorderIndexesMap
=
new
HashMap
<>();
public
TreeNode
buildBinaryTree
(
int
[]
preorder
,
int
[]
inorder
) {
// Populate the hash map with the inorder values and their indexes.
for
(
int
i
=
0
;
i
<
inorder
.
length
;
i
++) {
inorderIndexesMap
.
put
(
inorder
[
i
],
i
);
}
// Build the tree and return its root node.
return
buildSubtree
(
0
,
inorder
.
length
-
1
,
preorder
,
inorder
);
}
private
TreeNode
buildSubtree
(
int
left
,
int
right
,
int
[]
preorder
,
int
[]
inorder
) {
// Base case: if no elements are in this range, return None.
if
(
left
>
right
) {
return
null
;
}
int
val
=
preorder
[
preorderIndex
];
// Set 'inorderIndex' to the index of the same value pointed at by
// 'preorderIndex'.
int
inorderIndex
=
inorderIndexesMap
.
get
(
val
);
TreeNode
node
=
new
TreeNode
(
val
);
// Advance 'preorderIndex' 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
);
node
.
right
=
buildSubtree
(
inorderIndex
+
1
,
right
,
preorder
,
inorder
);
return
node
;
}
}
Back
|
FazBrowse Home
|
New Git URL