1
- /*
2
- Breadth First Tree Traversal or level order traversal implementation in javascript
3
- Author: @GerardUbuntu
4
- */
5
-
1
+ /**
2
+ * Represents a node in a binary tree.
3
+ */
6
4
class Node {
5
+ /**
6
+ * Creates a new node with the specified data.
7
+ * @param {* } data The data to be stored in the node.
8
+ */
7
9
constructor ( data ) {
8
10
this . data = data
9
11
this . left = null
10
12
this . right = null
11
13
}
12
14
}
13
15
16
+ /**
17
+ * Represents a binary tree data structure.
18
+ */
14
19
class BinaryTree {
20
+ /**
21
+ * Creates a new binary tree with an empty root.
22
+ */
15
23
constructor ( ) {
16
24
this . root = null
17
25
}
18
26
27
+ /**
28
+ * Performs breadth-first traversal of the binary tree iteratively.
29
+ * @returns {Array } An array containing the data of nodes visited in breadth-first order.
30
+ */
19
31
breadthFirstIterative ( ) {
20
32
const traversal = [ ]
21
33
if ( this . root ) {
@@ -34,6 +46,10 @@ class BinaryTree {
34
46
return traversal
35
47
}
36
48
49
+ /**
50
+ * Performs breadth-first traversal of the binary tree recursively.
51
+ * @returns {Array } An array containing the data of nodes visited in breadth-first order.
52
+ */
37
53
breadthFirstRecursive ( ) {
38
54
const traversal = [ ]
39
55
const h = this . getHeight ( this . root )
@@ -43,7 +59,11 @@ class BinaryTree {
43
59
return traversal
44
60
}
45
61
46
- // Computing the height of the tree
62
+ /**
63
+ * Computes the height of the tree starting from the specified node.
64
+ * @param {Node } node The node from which to compute the height.
65
+ * @returns {number } The height of the tree.
66
+ */
47
67
getHeight ( node ) {
48
68
if ( node === null ) {
49
69
return 0
@@ -53,6 +73,12 @@ class BinaryTree {
53
73
return lheight > rheight ? lheight + 1 : rheight + 1
54
74
}
55
75
76
+ /**
77
+ * Traverses the specified level of the tree and adds nodes' data to the traversal array.
78
+ * @param {Node } node The current node being traversed.
79
+ * @param {number } levelRemaining The remaining level to traverse.
80
+ * @param {Array } traversal The array to store the traversal result.
81
+ */
56
82
traverseLevel ( node , levelRemaining , traversal ) {
57
83
if ( node === null ) {
58
84
return
0 commit comments