Nil*_*wal 0 binary-tree max min
我已经实现了函数来查找二叉树的max和min元素.但我得到了错误的输出.
函数查找二叉树的最大值.
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;
}
Run Code Online (Sandbox Code Playgroud)
函数查找二叉树的最小值.
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;
}
Run Code Online (Sandbox Code Playgroud)
输出:树32767的最大值
树的最小值为0
private int minElem(Node node) {
int min= node.element;
if(node.left != null) {
min = Math.min(min, minElem(node.left));
}
if(node.right != null) {
min = Math.min(min, minElem(node.right));
}
return min;
}
Run Code Online (Sandbox Code Playgroud)