我试图按顺序遍历二叉搜索树,并将数据(已排序)放入数组中。 由于某种原因,指向数组中当前位置的指针没有向右移动。
这是DS的声明:
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
答案 0 :(得分: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;
}