最佳答案
有没有人可以帮助我理解以下莫里斯顺序树遍历算法没有使用堆栈或递归?我试图理解它是如何工作的,但它只是逃避我。
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
我知道这个树的修改方式是 current node
,是 right subtree
中 max node
的 right child
,并且使用这个属性进行无序遍历。但除此之外,我就迷失了。
编辑:
找到了附带的 c + + 代码。我很难理解修改后的树是如何恢复的。神奇之处在于 else
子句,一旦右叶被修改,就会命中它。详细信息见代码:
/* 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 */
}