Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 16281be

Browse files
committed
update: Binary Tree (!BST) added
1 parent 75b69be commit 16281be

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
module.exports = class Node {
2+
constructor(value) {
3+
this.value = value;
4+
this.leftChild = null; // will be a node
5+
this.rightChild = null; // will be a node
6+
}
7+
};
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
const Node = require('./Node');
2+
3+
class BinaryTree {
4+
constructor(arr) {
5+
if (!Array.isArray(arr)) {
6+
throw new Error('Invalid argument to create a Binary Tre');
7+
}
8+
this.root = this.createBinaryTree(this.root, arr, 0);
9+
}
10+
11+
// eslint-disable-next-line class-methods-use-this
12+
createBinaryTree(root, arr, i) {
13+
if (i < arr.length) {
14+
// eslint-disable-next-line no-param-reassign
15+
root = new Node(arr[i]);
16+
// eslint-disable-next-line no-param-reassign
17+
root.leftChild = this.createBinaryTree(root.leftChild, arr, 2 * i + 1);
18+
// eslint-disable-next-line no-param-reassign
19+
root.rightChild = this.createBinaryTree(root.rightChild, arr, 2 * i + 2);
20+
}
21+
return root;
22+
}
23+
24+
traversePreorder(root) {
25+
let arr = [];
26+
27+
if (root === null) return arr;
28+
// push node to arr
29+
arr.push(root.value);
30+
31+
// push left node
32+
const left = this.traversePreorder(root.leftChild);
33+
arr = [...arr, ...left];
34+
35+
// push right node
36+
const right = this.traversePreorder(root.rightChild);
37+
arr = [...arr, ...right];
38+
39+
return arr;
40+
}
41+
42+
preOrder() {
43+
return this.traversePreorder(this.root);
44+
}
45+
}
46+
47+
// const bt = new BinaryTree([1, 2, 3, 4, 5, 6]);
48+
// console.log(bt.root);
49+
// console.log(bt.preOrder());
50+
51+
module.exports = BinaryTree;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /