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 db5350c

Browse files
author
Swastikyadav
committed
Implement the insert method on binary search tree node class
1 parent 0a3d5e6 commit db5350c

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

‎DsAlgo-Questions/24-binarySearchTree.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/* Binary Search Tree !== Binary Tree
2+
| |
3+
Sorted Not Sorted
4+
5+
1. Implement the node class to create a binary search tree. The constructor should initialize values 'data', 'left', and 'right'.
6+
7+
2. Implement the 'insert' method for the Node class. Insert should accept an argument 'data', then create and insert a new node at the appropriate location in the tree.
8+
*/
9+
10+
class Node {
11+
constructor(data) {
12+
this.data = data;
13+
this.left = null;
14+
this.right = null;
15+
}
16+
17+
insert(data) {
18+
if (data < this.data && this.left) {
19+
this.left.insert(data);
20+
} else if (data < this.data) {
21+
this.left = new Node(data);
22+
} else if (data > this.data && this.right) {
23+
this.right.insert(data);
24+
} else if (data > this.data) {
25+
this.right = new Node(data);
26+
}
27+
}
28+
}

0 commit comments

Comments
(0)

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