searching for numbers in avl tree

I am trying to write code to search through an avl tree for a number. Part of it is working for example I enter the numbers 2,5,9 into the tree.
I then search for 9, then 5 then 2 and it tells me 2 is not in the tree.
I think I need point the search at the root every time it searches but not sure how to do that. The code just needs to say if the number is in the tree or not.

heres the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
void AVLtree::SearchTree(TreeNode *tree, int item)
{
	TreeNode * ls;
	TreeNode * rs;

	TreeNode*ptr, *save;
	bool flag = false;

	if(tree == NULL)
	{
	cout << "The tree is empty\n";
	return;
	}
	
	if (tree->info == item)
	{
	cout << "Item " << item << " is the root\n";
	tree->left = NULL;
	tree->right = NULL;
	return;
	}
	if( item < tree->info)
	{
	ptr = tree->left;
	save = tree;
	}
	else
	{
	ptr = tree->right;
	save = tree;
	}
	while(ptr!=NULL)
	{
		if(item == ptr->info)
		{
		flag = true;
		cout << "Item " << item << " was found in the tree\n\n";
		ls = ptr;
		rs = save;
		}
		if(item < ptr->info)
		ptr = ptr->left;
		else
		ptr = ptr->right;
	}
	if(flag == false)
	{
		cout << "Item " << item << " is not in the tree\n";
		ls = NULL;
		rs = NULL;
		
		
	}
}
Last edited on
anyone?
1
2
3
4
5
6
7
	if (tree->info == item)
	{
	cout << "Item " << item << " is the root\n";
	tree->left = NULL;
	tree->right = NULL;
	return;
	}


What do you think this is doing? A search function should not modify the tree.

Presumably AVLtree is a class that represents a tree, so I'm not really sure why you're feeding it a TreeNode*

Generally a search function would signal to the calling code that it was successful or not. That's the point at which you should be using cout, not in the search function.

ok so what should i be doing instead? i need the tree to start at the root and go down all the nodes to see if the number is there
Topic archived. No new replies allowed.