JavaScript Data Structures - 35 - Binary Search Tree Search

preview_player
Показать описание

📱 Follow Codevolution

Binary Search Tree Search
JavaScript Data Structures
Data Structures in JavaScript
Рекомендации по теме
Комментарии
Автор

I really thank you so much for your amazing videos.

moseschris
Автор

Searching can also be done in iterative way using while like in this example :
search(value) {
if (this.isEmpty()) {
return false;
} else {
let current = this.root;
while (current) {
if (value === current.value) {
return true;
} else if (value < current.value) {
current = current.left;
} else {
current = current.right;
}
}
return false;
}
}

prazzydh
Автор

You could further optimize the search function call by assigning this.root as a default value for the root argument.

search(value, root = this.root) {
if (!root) {
return false;
} else {
if (root.value === value) {
return true;
} else if (value < root.value) {
return this.search(value, root.left);
} else {
return this.search(value, root.right);
}
}
}

console.log(bst.search(10));
console.log(bst.search(5));
console.log(bst.search(15));
console.log(bst.search(20));

Grantoed
Автор

line 35 - make use of the isEmpty() method for code cleanliness

TheYinyangman
Автор

but, in the if(!root), how is checking if the root parameter is equal to this.root?? dont it need to be if(root!==this.root)?

urieldahan
Автор

I think someone asked this too but how come in the search method the first if statement doesnt check for this.root and checks for just root instead. how will it know what is 'root'. its not defined as i understand

XX-fvkc
Автор

Why did we return in search and not while inserting?

hassanrasoolsiddiqui
Автор

After explanations from the author, I paused this video and tried to implement the method myself.

Is my implementation worse? I am a noob at algorithms. I just want to check my level. By the way, where can I check used memory and runtime the easiest way?

search(value) {
if(!this.root) {
return false;
} else {
let curRoot = this.root;

while (curRoot.value != value) {
if (curRoot.value > value) {
if (curRoot.left != null) {
curRoot = curRoot.left
} else {
return false;
}
} else {
if (curRoot.right != null) {
curRoot = curRoot.right;
} else {
return false;
}
}
}

if (curRoot.value === value) {
return true;
} else {
return false;
}
}
}

oksanaozcan
Автор

why not to write search with single argument like below?
search(value) {
return this.searchLeftRight(this.root, value)
}

searchLeftRight(root, value) {
if (!root) {
return false
}
if (root.value === value) {
return true
}
if (value < root.value) {
return this.searchLeftRight(root.left, value)
} else {
return this.searchLeftRight(root.right, value)
}
}

ajayghori
join shbcf.ru