-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary-tree.js
42 lines (39 loc) · 908 Bytes
/
binary-tree.js
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
/*
Algorithm to return the root node of a binary search tree that matches the given preorder traversal.
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
const createBST = (number, node) => {
if(number < node.val) {
if(node.left === null) {
node.left = new TreeNode(number)
}
else {
createBST(number, node.left)
}
}
else {
if(node.right === null) {
node.right = new TreeNode(number)
}
else {
createBST(number, node.right)
}
}
};
/**
* @param {number[]} preorder
* @return {TreeNode}
*/
const bstFromPreorder = function(preorder) {
const head = new TreeNode(preorder[0]);
for(let i=1;i<preorder.length;i++) {
createBST(preorder[i], head)
}
return head
};