有人可以在不使用堆栈或递归的情况下帮助我了解以下Morris有序树遍历算法吗?我试图理解它是如何工作的,但是它只是在逃避我。
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 child
,将max node
in 做成in,right subtree
并使用此属性进行有序遍历。但是除此之外,我迷路了。
编辑:找到了此随附的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 */
}
pre->right = NULL;