MCPcopy Create free account
hub / github.com/TheAlgorithms/JavaScript / BinaryTree

Class BinaryTree

Trees/BreadthFirstTreeTraversal.js:14–67  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

12}
13
14class BinaryTree {
15 constructor() {
16 this.root = null
17 }
18
19 breadthFirstIterative() {
20 const traversal = []
21 if (this.root) {
22 traversal.push(this.root)
23 }
24 for (let i = 0; i < traversal.length; i++) {
25 const currentNode = traversal[i]
26 if (currentNode.left) {
27 traversal.push(currentNode.left)
28 }
29 if (currentNode.right) {
30 traversal.push(currentNode.right)
31 }
32 traversal[i] = currentNode.data
33 }
34 return traversal
35 }
36
37 breadthFirstRecursive() {
38 const traversal = []
39 const h = this.getHeight(this.root)
40 for (let i = 0; i !== h; i++) {
41 this.traverseLevel(this.root, i, traversal)
42 }
43 return traversal
44 }
45
46 // Computing the height of the tree
47 getHeight(node) {
48 if (node === null) {
49 return 0
50 }
51 const lheight = this.getHeight(node.left)
52 const rheight = this.getHeight(node.right)
53 return lheight > rheight ? lheight + 1 : rheight + 1
54 }
55
56 traverseLevel(node, levelRemaining, traversal) {
57 if (node === null) {
58 return
59 }
60 if (levelRemaining === 0) {
61 traversal.push(node.data)
62 } else {
63 this.traverseLevel(node.left, levelRemaining - 1, traversal)
64 this.traverseLevel(node.right, levelRemaining - 1, traversal)
65 }
66 }
67}
68
69export { BinaryTree, Node }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected