diff --git a/README.md b/README.md index 54971425..94ab8d6f 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ Collection of interview questions with Unit Tests. Problems includes Data Struct - [Doubly Linked List](src/_DataStructures_/DoublyLinkedList) - [Trees](src/_DataStructures_/Trees) + - [Binary Tree (creation using level order)](src/_DataStructures_/Trees/BinaryTree) - [Binary Search Tree](src/_DataStructures_/Trees/BinarySearchTree) - [Find kth maximum in a BinarySearchTree](src/_DataStructures_/Trees/BinarySearchTree/find-kth-max) - [Find kth minimum in a BinarySearchTree](src/_DataStructures_/Trees/BinarySearchTree/find-kth-min) diff --git a/src/_DataStructures_/Trees/BinaryTree/Node.js b/src/_DataStructures_/Trees/BinaryTree/Node.js new file mode 100644 index 00000000..2b515b2a --- /dev/null +++ b/src/_DataStructures_/Trees/BinaryTree/Node.js @@ -0,0 +1,7 @@ +module.exports = class Node { + constructor(value) { + this.value = value; + this.leftChild = null; // will be a node + this.rightChild = null; // will be a node + } +}; diff --git a/src/_DataStructures_/Trees/BinaryTree/index.js b/src/_DataStructures_/Trees/BinaryTree/index.js new file mode 100644 index 00000000..f30999ad --- /dev/null +++ b/src/_DataStructures_/Trees/BinaryTree/index.js @@ -0,0 +1,51 @@ +const Node = require('./Node'); + +class BinaryTree { + constructor(arr) { + if (!Array.isArray(arr) || !arr.length) { + throw new Error('Invalid argument to create a Binary Tre'); + } + this.root = this.createBinaryTree((this.root = null), arr, 0); + } + + // eslint-disable-next-line class-methods-use-this + createBinaryTree(root, arr, i) { + if (i < arr.length) { + // eslint-disable-next-line no-param-reassign + root = new Node(arr[i]); + // eslint-disable-next-line no-param-reassign + root.leftChild = this.createBinaryTree(root.leftChild, arr, 2 * i + 1); + // eslint-disable-next-line no-param-reassign + root.rightChild = this.createBinaryTree(root.rightChild, arr, 2 * i + 2); + } + return root; + } + + traversePreorder(root) { + let arr = []; + + if (root === null) return arr; + // push node to arr + arr.push(root.value); + + // push left node + const left = this.traversePreorder(root.leftChild); + arr = [...arr, ...left]; + + // push right node + const right = this.traversePreorder(root.rightChild); + arr = [...arr, ...right]; + + return arr; + } + + preOrder() { + return this.traversePreorder(this.root); + } +} + +// const bt = new BinaryTree([1, 2, 3, 4, 5, 6]); +// console.log(bt.root); +// console.log(bt.preOrder()); + +module.exports = BinaryTree;

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