2016-11-19 25 views
0

我想找到一個節點的rigate子樹中的最小數字,下面的代碼是我認爲是解決方案,但它不能正常工作。這段代碼有什麼問題?如何找到右子樹上的最小數字

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; 
} 
+0

什麼是「小」,它在哪裏聲明? – templatetypedef

+0

我會說,這等於在常規樹中找到最小的,但不是將根傳遞給該函數,而是傳遞正確的子樹... – Copperfield

回答

1

我使用右子樹指針和n.left左子樹指針n.right

只需調用函數最小(n.right);最小是一個函數,它會在二叉樹中找到最小值

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; 
} 
相關問題