Last active
February 5, 2023 09:11
-
-
Save jordanrios94/8c73108114adc0f67eb58ee32c409d1a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
- Implement the Node class to create a binary search tree. The constructor should initialize values 'data', 'left', and 'right'. | |
- Implement the 'insert' method for the Node class. Insert should accept an argument 'data', then create an insert a new node at the appropriate location in the tree. | |
- Implement the 'contains' method for the Node class. Contains should accept a 'data' argument and return the Node in the tree with the same value. | |
*/ | |
class Node { | |
constructor(data) { | |
this.data = data; | |
this.left = null; | |
this.right = null; | |
} | |
insert(data) { | |
if (data < this.data && this.left) { | |
this.left.insert(data); | |
} else if (data < this.data) { | |
this.left = new Node(data); | |
} else if (data > this.data && this.right) { | |
this.right.insert(data); | |
} else if (data > this.data) { | |
this.right = new Node(data); | |
} | |
} | |
contains(data) { | |
if (this.data === data) { | |
return this; | |
} | |
if (this.data < data && this.right) { | |
return this.right.contains(data); | |
} else if (this.data > data && this.left) { | |
return this.left.contains(data); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
corrected my original contains method