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 406023b

Browse files
author
Swastikyadav
committed
Create a tree DS class with depth first and breadth first method
1 parent 0986ee0 commit 406023b

File tree

1 file changed

+57
-6
lines changed

1 file changed

+57
-6
lines changed

‎DsAlgo-Questions/22-trees.js

Lines changed: 57 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
44
2. Create a tree class. The tree constuctor should initialize a 'root' property to null.
55
6-
3. Implement 'traverseBFS' and 'traverseDFS' on the trees class.
6+
3. Implement 'traverseBFS' and 'traverseDFS' on the trees class. Each method should accept a function that gets called with each element in the tree.
77
*/
88

99
class Node {
@@ -13,8 +13,13 @@ class Node {
1313
}
1414

1515
// Add a new node to the children of current node.
16-
add(data) {
17-
this.children.push(new Node(data));
16+
add(data, children=[]) {
17+
const newNode = new Node(data);
18+
children.forEach(elm => {
19+
newNode.children.push(new Node(elm));
20+
});
21+
22+
this.children.push(newNode);
1823
}
1924

2025
// Remove a data from the children of current node.
@@ -28,7 +33,53 @@ class Node {
2833
};
2934

3035
class Tree {
31-
constructor() {
32-
this.root = null;
36+
constructor(root) {
37+
this.root = root || null;
38+
}
39+
40+
// Breadth first search (horizontal search)
41+
traverseBFS(callback) {
42+
const arr = [this.root];
43+
44+
while (arr.length) {
45+
const node = arr.shift();
46+
47+
// The key difference - Adding childrens to the end of array.
48+
arr.push(...node.children);
49+
callback(node);
50+
}
51+
}
52+
53+
// Depth first search (vertical serach)
54+
traverseDFS(callback) {
55+
// this.root.children.forEach(node => {
56+
// callback(node);
57+
58+
// const newTree = new Tree(node);
59+
60+
// newTree.traverseDFS(callback);
61+
// });
62+
63+
const arr = [this.root];
64+
65+
while (arr.length) {
66+
const node = arr.shift();
67+
68+
// The key difference - Adding childrens to the start of array.
69+
arr.unshift(...node.children);
70+
callback(node);
71+
}
3372
}
34-
};
73+
};
74+
75+
const node = new Node(20);
76+
77+
node.add(0, [12, -2, 1]);
78+
node.add(40);
79+
node.add(-15, [-2]);
80+
81+
const tree = new Tree(node);
82+
83+
tree.traverseBFS((node) => console.log(node.data));
84+
console.log("-------------");
85+
tree.traverseDFS((node) => console.log(node.data));

0 commit comments

Comments
(0)

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