-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreorder.js
46 lines (37 loc) · 994 Bytes
/
preorder.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
43
44
45
46
const tree = convertBinaryTree("31,52,,32,64,43,,34".split(","));
console.log(getNodeVal(tree));
function getNodeVal(node, result = []) {
result.push(node.val);
node.left && getNodeVal(node.left, result);
node.right && getNodeVal(node.right, result);
return result;
}
function convertBinaryTree(arr) {
let root;
let insertNode = function(parentNode, childNode) {
if (!childNode || childNode.val == "") return;
if (childNode.val < parentNode.val) {
if (parentNode.left === null) {
parentNode.left = childNode;
} else {
insertNode(parentNode.left, childNode)
}
} else {
if (parentNode.right === null) {
parentNode.right = childNode;
} else {
insertNode(parentNode.right, childNode)
}
}
}
arr.forEach( val => {
let node = {
val: val,
left: null,
right: null
};
if (root) insertNode(root, node);
else root = node;
});
return root;
}