我已经实现了查找二叉树的最大和最小元素的函数。但我得到了错误的输出。
查找二叉树最大值的函数。
int FindMax(struct TreeNode *bt)
{
//get the maximum value of the binary tree...
int max;
//get the maximum of the left sub-tree.
int left;
//get the maximum of the right sub-tree.
int right;
//get the root of the current node.
int root;
if(bt!=NULL)
{
root=bt->data;
//Call the left tree recursively....
left=FindMax(bt->leftChild);
//Call the right tree recursively...
right=FindMax(bt->rightChild);
if(left > right)
{
max=left;
}
else
{
max=right;
}
if(max < root)
{
max=root;
}
}
return max;
}
查找二叉树最小值的函数。
int FindMin(struct TreeNode *bt)
{
//get the minimum value of the binary tree...
int min;
//get the minimum of the left sub-tree.
int left;
//get the minimum of the right sub-tree.
int right;
//get the root of the current node.
int root;
if(bt!=NULL)
{
root=bt->data;
//Call the left tree recursively....
left=FindMin(bt->leftChild);
//Call the right tree recursively...
right=FindMin(bt->rightChild);
if(left < right)
{
min=left;
}
else
{
min=right;
}
if(min > root)
{
min=root;
}
}
return min;
}
输出:树的最大值 32767
树的最小值 0