I want to find the smallest number in a rignt subtree of a node, and this code below is what I thought that was the solution, but its not working properly. What is wrong with this code?
我想在一个节点的严格子树中找到最小的数字,下面这段代码就是我认为的解决方案,但它无法正常工作。这段代码有什么问题?
int small; // Where the smallest value is stored
int smallest(Node n)
{
if(n.info < small && aux != 0) small = n.info;
if(aux == 0)
{
aux = 1;
small = n.dir.info;
if(n!=NULL && n.dir!=NULL) return smallest(n.dir);
}
else{
if(n.dir != NULL) return smallest(n.dir);
if(n.esq != NULL) return smallest(n.esq);
}
return small;
}
1 个解决方案
#1
1
I am using n.right for right subtree pointer and n.left for left subtree pointer
我使用n.right作为右子树指针,n.left用于左子树指针
Just call the function smallest(n.right); smallest is a function that will find the smallest value in a binary tree
只需调用函数最小(n.right); smallest是一个可以在二叉树中找到最小值的函数
int smallest(Node n){
if( n==NULL ) return INF; // replace INF with the maximum value that int can hold in your system like 2147483647
int left_small = smallest(n.left); // smallest value in left subtree
int right_small = smallest(n.right); // smallest value in right subtree
int ans = n.info;
if( left_small < ans ) ans = left_small;
if( right_small < ans ) ans = right_small;
return ans;
}
#1
1
I am using n.right for right subtree pointer and n.left for left subtree pointer
我使用n.right作为右子树指针,n.left用于左子树指针
Just call the function smallest(n.right); smallest is a function that will find the smallest value in a binary tree
只需调用函数最小(n.right); smallest是一个可以在二叉树中找到最小值的函数
int smallest(Node n){
if( n==NULL ) return INF; // replace INF with the maximum value that int can hold in your system like 2147483647
int left_small = smallest(n.left); // smallest value in left subtree
int right_small = smallest(n.right); // smallest value in right subtree
int ans = n.info;
if( left_small < ans ) ans = left_small;
if( right_small < ans ) ans = right_small;
return ans;
}