如何在右子树上找到最小的数字

时间:2016-11-19 16:36:08

标签: data-structures tree binary-tree

我想在一个节点的严格子树中找到最小的数字,下面的代码就是我认为的解决方案,但它不能正常工作。这段代码有什么问题?

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 个答案:

答案 0 :(得分:1)

我使用n.right作为右子树指针,n.left用于左子树指针

只需调用函数最小(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;
}