Explique a travessia de árvore de ordem de Morris sem usar pilhas ou recursão
Alguém pode me ajudar a entender o seguinte algoritmo de travessia de árvore inorder da Morris sem usar pilhas ou recursão? Eu estava tentando entender como isso funciona, mas está me escapand
1. Initialize current as root
2. While current is not NULL
If current does not have left child
a. Print current’s data
b. Go to the right, i.e., current = current->right
Else
a. In current's left subtree, make current the right child of the rightmost node
b. Go to this left child, i.e., current = current->left
Entendo que a árvore é modificada de uma maneira que ocurrent node
, é feito oright child
domax node
emright subtree
e use essa propriedade para travessia de ordem. Mas além disso, estou perdid
EDIT: Encontrei este código c ++ que o acompanha. Eu estava tendo dificuldade para entender como a árvore é restaurada depois de modificada. A mágica está emelse
, que é atingida quando a folha direita é modificada. Veja o código para obter detalhes:
/* Function to traverse binary tree without recursion and
without stack */
void MorrisTraversal(struct tNode *root)
{
struct tNode *current,*pre;
if(root == NULL)
return;
current = root;
while(current != NULL)
{
if(current->left == NULL)
{
printf(" %d ", current->data);
current = current->right;
}
else
{
/* Find the inorder predecessor of current */
pre = current->left;
while(pre->right != NULL && pre->right != current)
pre = pre->right;
/* Make current as right child of its inorder predecessor */
if(pre->right == NULL)
{
pre->right = current;
current = current->left;
}
// MAGIC OF RESTORING the Tree happens here:
/* Revert the changes made in if part to restore the original
tree i.e., fix the right child of predecssor */
else
{
pre->right = NULL;
printf(" %d ",current->data);
current = current->right;
} /* End of if condition pre->right == NULL */
} /* End of if condition current->left == NULL*/
} /* End of while */
}