|
-
January 13th, 2009, 03:04 PM
#1
Search algorithm for a binary search tree.
Hi everyone, hope everything is going good? , I just sat a Data Structures and Algorithms exam paper today, it went pretty good, however I wanted to get a few things straight and to help me further understand some concepts. Can anyone help me with question below.
The exam question was the very final question and it goes as follows:
Write a recursive search method that goes through a binary search tree, searching for an element at node p, if the node p is found in the tree return true, else return false.
I don't have the exam paper they took it away but that is how I remember the question. My answer was as follows:
Code:
Boolean search(Tree tree, TreeNode p){
If(tree.TreeRoot == null){
return false;
}
If(p < tree.TreeRoot){
search(tree.left, p);
If(p == el){
return true;
}
}
If(p > tree.TreeRoot){
search(tree.right, p);
If(p == el){
return true;
}
}
return false;
}
PS: el is the element.
Hopefully you guys can give me helpful tips in improve the way I go about writing algorithms and show where I've gone wrong, and what I need to change etc.
Thanks,
Hass
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|