C++ Find Min and Max element in a BST

对于一个二叉搜索树, 要想找到这棵树的最小元素值, 我们只需要从树根开始, 沿着left 孩子指针一直走, 知道遇到NULL(即走到了叶子), 那么这个叶子节点就存储了这棵二叉搜索树的最小元素。 同理, 从根节点开始, 沿着right 孩子指针, 最终找到的是最大关键字的节点。

 也就是说寻找BST最小关键字的元素和最大关键字的元素的代码是对称的。伪代码如下:

TREE_MINIMUM(x)

while x.left != NULL

   x= x.left

return  x

寻找最大关键字元素的伪代码:

TREE_MAXMUM(x)

while x.right != NULL

   x= x.right

return  x

对应的C++ 代代码如下:

树的节点定义如下:

// C style of using struct, in C++ simply below:
/*
struct Node {
	int data;
    Node *left;
    Node *right;
};

*/
struct Node {
	int data;
	struct Node *left;
	struct Node *right;
};


寻找最大值和最小值可以使用递归的方式, 也可以使用迭代的办法(iterative solution), 下面首先给出迭代的解决办法。 对应函数为:

//Function to find minimum in a BST tree.
Node* FindMin(Node* root)
{
	while(root->left != NULL) root = root->left;
	return root;
}

//Function to find maximum in a BST tree.
Node* FindMin(Node* root)
{
	while(root->right != NULL) root = root-> right;
	return root; // okay , this root is local variables
}

注意, 上述找到的只是具有最大值和最小值的元素节点。 如果想返回最大的值, 直接可以修改为如下(也可以在主程序中直接使用返回的节点-> data 即可).。 但是上面的代码还是有点问题的。 设想, 如果我们的BST是empty的, 我们需要 throw some error, 下面给出一个更好的返回值的代码(只给出查找最小元素值并返回的代码):

int FindMin(Node* root)
{
    if(root == NULL) {
       cout << "Error: BST is empty \n";
       return -1;// print error  and return -1
    }
    Node* current = root; // 不用额外什么curret 变量, 也可以直接使用root变量, 因为root是Local variable
	while(current -> left != NULL) {
	   current = current -> left;
	}
	return current -> data;
}

将上面程序改为:

int FindMin(Node* root)
{
    if(root == NULL) {
       cout << "Error: BST is empty \n";
       return -1;// print error  and return -1
    }	
    while(root -> left != NULL) {
	   root = root -> left;
	}
	return root -> data;// 注意root 为Local variable
}

上述是使用迭代的办法。 由于树时递归的数据结构, 我们当然可以使用递归的办法查找最大值和最小值。 以查找最小元素为例, 从根节点开始, 查找树的根节点的左子树的最小值, 然后查找下一个节点为根节点的左子树的最小值。。。, 直至遇到了空子树, 返回。 程序如下所示:

int FindMin2(Node* root) {
   if(root == NULL) {
      cout << "Error: Tree is empty\n";
      return -1;
   }
   else if(root -> left == NULL) {
      return root -> data; // base case
   }
   //search the left subtree
   return FindMin(root -> left);
}




 


 

 

 



 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值