ProAnswers.org

algorithm Search for a key in a Binary Search Tree

algorithm Search for a key in a Binary Search Tree

Recursive Version

						01
					
						02
					
						03
					
						04
					
						05
					
						06
					
						07
					
						08
					
						09
					
						10
				
				
					
						
							int search_bst(node *root, int x){
						
							    if(root == NULL)
						
							        return 0;
						
							    if(root->data == x)
						
							        return 1;
						
							    if(root->data < x)
						
							        return search_bst(root->left, x);
						
							    else
						
							        return search_bst(root->right, x);
						
							}
					
				
			
		
	



Iterative Version



 


	
		
			
				01
			
				02
			
				03
			
				04
			
				05
			
				06
			
				07
			
				08
			
				09
			
				10
			
				11
			
				12
			
				13
			
				14
		
		
			
				
					int search_bst(node *root, int x){
				
					    if(root == NULL)
				
					        return 0;
				
					    while(root != NULL && x != root->data){
				
					        if(root->data < x)
				
					            root = root->left;
				
					        else
				
					            root = root->right;
				
					    }
				
					    if(root == NULL)
				
					        return 0;
				
					    else
				
					        return 1;
				
					}