Binary search tree lookup

Find a certain value

The search starts from the root node. If the tree is empty, NULL is returned.
If the search tree is not empty, the root node key value is compared with X and processed differently:

  • If X is less than the key value of the root node, just continue to search in the left subtree
  • If X is greater than the key value of the root node, just continue to search in the right subtree
  • If the two are equal, the search is complete, and the pointer to this node is returned
//定义二叉树 
typedef struct TreeNode *BinTree;
typedef BinTree Position;
typedef int ElementType;
struct TreeNode
{
    
    
	ElementType data;
	BinTree left;
	BinTree right;
};

Position Find(ElementType x,BinTree bst)
{
    
    
	while(bst)
	{
    
    
		if(x>bst->data)
			bst=bst->right;
		else if(x<bst->data)
			bst=bst->left;
		else
			return bst;
	}
	return NULL;
}

Find the maximum

The largest element must be at the end node of the rightmost branch of the tree

Position FindMax(BinTree bst)
{
    
    
	if(bst)
		while(bst->right)
			bst=bst->right;
	return bst;
 } 

Find the smallest value

The smallest element must be at the end node of the leftmost branch of the tree

 Position FindMin(BinTree bst)
 {
    
    
 	if(bst)
 		while(bst->left)
 			bst=bst->left;
 	return bst;
 }

Guess you like

Origin blog.csdn.net/m0_54621932/article/details/114140353