Finding a Node In a BST

VisualGo Demonstration
VisualGo Demonstration
  • Starting at the root
  • Check if there is a root, if not — we’re done searching!
  • If there is a root, check if the value of the new node is the value we are looking for. If we found it, we’re done!
  • If not, check to see if the value is greater than or less than the value of the root
  • If it is greater
  • Check to see if there is a node to the right
  • If there is, move to that node and repeat these steps
  • If there is not, we’re done searching!
  • If it is less
  • Check to see if there is a node to the left
  • If there is, move to that node and repeat these steps
  • If there is not, we’re done searching!
class Node {     constructor(value){     this.value = value;     this.right = null;     this.left = null;    }} class BinarySearchTree{    constructor(){       this.root = null;   }
find(value){
if (this.root === null) return false;
var current = this.root,
found = false;
while(current && !found){
if(value < current.value){
current = current.left;
} else if(value > current.value){
current = current.right;
} else {
found = true
}
}
}
if(!found) return undefined;
return current
}
find(value){if(this.root === null) return false;
var current = this.root;
var found = false
while(current && !found )
current = current.left;
} else if(value > current.value){
current = current.right;
found = true
if(!found) return undefined;
return current

True & false Version

contains (value){
if (this.root === null) return false;
var current = this.root,
found = false;
while(current && !found){
if(value < current.value){
current = current.left;
} else if(value > current.value){
current = current.right;
} else {
return true
}
}
}

return false
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Soner Mezgitci

Soner Mezgitci

31 Followers

Software Engineer | Ruby on Rails | JavaScript | HTML5 | CSS | PostgreSQL | React | Redux