#include ONCE "window9.bi"

Sub tree_add_node(x As Long, Byref MyTree As Node Ptr) export
	
	If (MyTree = 0) Then 
		
		MyTree=new Node
		
		if MyTree = 0 then
			
			print "Allocated memory error in tree_add_node!"
			
			exit sub
			
		EndIf
		
		MyTree->x=x
		
		MyTree->l=0 
		
		MyTree->r=0 
		
	Endif
	
	If (x<MyTree->x) Then   
		
		If (MyTree->l<>0) Then
			
			tree_add_node(x,MyTree->l) 
			
		Else 
			
			MyTree->l=new Node  
			
			if MyTree->l then
				
				MyTree->l->l=0 : MyTree->l->r=0 
				
				MyTree->l->x=x
				
			else
				
				print "Allocated memory error in tree_add_node!"
				
				exit sub
				
			endif
			
		Endif
		
	Endif
	
	If (x>MyTree->x) Then  
		
		If (MyTree->r<>0) Then
			
			tree_add_node(x,MyTree->r) 
			
		Else 
			
			MyTree->r=new Node 
			
			if MyTree->r then
				
				MyTree->r->l=0:MyTree->r->r=0
				
				MyTree->r->x=x
				
			else
				
				print "Allocated memory error in tree_add_node!"
				
			endif
			
		Endif
		
	Endif
	
End Sub


Function tree_find_node(ikey As Long, MyTree As Node Ptr) As Node Ptr export
	
	If MyTree = 0 OrElse MyTree->x = ikey Then Return MyTree
	
	If MyTree->x < ikey Then 
		
		Return tree_find_node(iKey,MyTree->r) 
		
	Else 
		
		Return tree_find_node(iKey,MyTree->l) 
		
	Endif
	
End Function

