2012-06-16 125 views
0

我正在嘗試遍歷二叉搜索樹的順序,並將數據(排序)放入數組中。 由於某些原因,指向數組中當前位置的指針不能正確移動。程序集:遍歷二叉搜索樹

這是DS的decleration:

TreeRoot DWORD    Null (left child) 
      DWORD Null (right child) 
      SDWORD 6 (numeric value) 

,這是我想寫的功能:

TreeToArray PROC 
    rootPtr=8; 
    ArrayPtr=rootPtr+4; 

    ;Saving the Registers 
    push ebp; 
    mov ebp,esp; 
    push esi; 
    push edx; 
    push ebx; 
    push edi; 
    push ecx; 

Check: 
    mov esi,rootPtr[ebp]; esi holds the current root 
    mov edi, ArrayPtr[ebp] ;edi holds the pointer to the array 
    cmp esi,Null ;if root=null 
    je Done2; 

LeftSubTree: 
    push edi 
    push BinTreeLeft[esi] 
    call TreeToArray; recursive call for left sub tree 

Visit: 
    mov ebx,BinTreeValue[esi] ;getting the value of the node 
    mov [edi],ebx 
    add edi,4 

RightSubTree: 
    push edi 
    push BinTreeRight[esi] 
    call TreeToArray; recursive call for right sub tree 

Done2: 
    pop ecx; 
    pop edi; 
    pop ebx 
    pop edx 
    pop esi 
    pop ebp 
    ret 8; 

TreeToArray ENDP 

回答

1

您的代碼現在看起來是這樣的(如果拼寫用C ):

typedef struct tNode 
{ 
    struct tNode* pLeftChild; 
    struct tNode* pRightChild; 
    int Value; 
} tNode; 

void TreeToArray(tNode* pNode, int* pArrayElement) 
{ 
    if (pNode == NULL) return; 

    TreeToArray(pNode->pLeftChild, pArrayElement); 

    *pArrayElement = pNode->Value; 
    pArrayElement++; 

    TreeToArray(pNode->pRightChild, pArrayElement); 
} 

只在進入右側子節點並忘記提前進行時纔會「移動」指針返回父節點時的指針。

你想要做的,而不是什麼是:

int* TreeToArray(tNode* pNode, int* pArrayElement) 
{ 
    if (pNode == NULL) return pArrayElement; 

    pArrayElement = TreeToArray(pNode->pLeftChild, pArrayElement); 

    *pArrayElement = pNode->Value; 
    pArrayElement++; 

    pArrayElement = TreeToArray(pNode->pRightChild, pArrayElement); 

    return pArrayElement; 
}