Ad
I Want To Search For Values In Binary Search Tree Using Iteration
Hello I wrote this method to search for values in my binary search tree but it is always returning false whether the value is found in my bst or not. can someone please tell me what's my mistake and how I can fix it.
public boolean search(int key) {
BinaryTreeNode subRoot = null;
while (subRoot != null)
{
if (key > subRoot.getData()) {
root = subRoot.getRight();
}
else if (key < subRoot.getData())
root = subRoot.getLeft();
else
System.out.println("Searching for " + key + ": found");
return true;
}
System.out.println("Searching for " + key + ": NOT found");
return false;
}
Ad
Answer
Not having more input this is everything I can do. You forgot to assign subRoot to root at the beginning. You here assigning values to your root in the loop this would lead to loss of data and most likely a infinite-loop. Plus your else statement had no brakets, so it would always return true if you entered the loop.
public boolean search(int key) {
BinaryTreeNode subRoot = root;
while (subRoot != null)
{
if (key > subRoot.getData())
subRoot = subRoot.getRight();
else if (key < subRoot.getData())
subRoot = subRoot.getLeft();
else{
System.out.println("Searching for " + key + ": found");
return true;
}
}
System.out.println("Searching for " + key + ": NOT found");
return false;
}
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad