Skip to content

Commit 9e01c43

Browse files
authored
Merge pull request knaxus#96 from knaxus/problems
Added Binary Tree
2 parents fb4feb4 + 580e3ba commit 9e01c43

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ Collection of interview questions with Unit Tests. Problems includes Data Struct
4242
- [Doubly Linked List](src/_DataStructures_/DoublyLinkedList)
4343

4444
- [Trees](src/_DataStructures_/Trees)
45+
- [Binary Tree (creation using level order)](src/_DataStructures_/Trees/BinaryTree)
4546
- [Binary Search Tree](src/_DataStructures_/Trees/BinarySearchTree)
4647
- [Find k<sup>th</sup> maximum in a BinarySearchTree](src/_DataStructures_/Trees/BinarySearchTree/find-kth-max)
4748
- [Find k<sup>th</sup> minimum in a BinarySearchTree](src/_DataStructures_/Trees/BinarySearchTree/find-kth-min)
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+
};
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) || !arr.length) {
6+
throw new Error('Invalid argument to create a Binary Tre');
7+
}
8+
this.root = this.createBinaryTree((this.root = null), 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)