刚开始接触到这个是因为算法导论习题10.4-5,其中有一句话说不能改变二叉树结构,即使临时改变也不行,个人就感觉改变二叉树结构也可以进行遍历。
搜索的过程中发现了morris 遍历,刚开始根本不相信如此短的代码可以使用无栈、O(1) 空间进行二叉树遍历,但深入之后才发现这个想法是如此的巧妙,感谢J Morris,不知这个Morris 和KMP中的Morris 是否是同一个人?
morris 中序遍历
- void bst_morris_inorder(struct bst_node *root)
- {
- struct bst_node *p = root, *tmp;
- while (p) {
- if (p->left == NULL) {
- printf("%d ", p->key);
- p = p->right;
- }
- else {
- tmp = p->left;
- while (tmp->right != NULL && tmp->right != p)
- tmp = tmp->right;
- if (tmp->right == NULL) {
- tmp->right = p;
- p = p->left;
- }
- else {
- printf("%d ", p->key);
- tmp->right = NULL;
- p = p->right;
- }
- }
- }
- }
morris traversal 原理很简单,利用所有叶子结点的right 指针,指向其后继结点,组成一个环,在第二次遍历到这个结点时,由于其左子树已经遍历完了,则访问该结点
如下图为morris 的一个示例
morris 前序遍历
- void bst_morris_preorder(struct bst_node *root)
- {
- struct bst_node *p = root, *tmp;
- while (p) {
- if (p->left == NULL) {
- printf("%d ", p->key);
- p = p->right;
- }
- else {
- tmp = p->left;
- while (tmp->right != NULL && tmp->right != p)
- tmp = tmp->right;
- if (tmp->right == NULL) {
- printf("%d ", p->key);
- tmp->right = p;
- p = p->left;
- }
- else {
- tmp->right = NULL;
- p = p->right;
- }
- }
- }
- }
morris 后序遍历
- static void bst_morris_reverse(struct bst_node *node, struct bst_node *last)
- {
- struct bst_node *p = node, *x, *y;
- if (p == last) {
- printf("%d ", last->key);
- return;
- }
- /* change right to parent pointer */
- x = p->right;
- for (;;) {
- if (x == last) {
- x->right = p;
- break;
- }
- y = x->right;
- x->right = p;
- p = x;
- x = y;
- }
- /* visit each */
- x = last;
- for (;;) {
- printf("%d ", x->key);
- if (x == node)
- break;
- x = x->right;
- }
- /* revert right pointer */
- p = last;
- x = last->right;
- for (;;) {
- if (x == node) {
- x->right = p;
- break;
- }
- y = x->right;
- x->right = p;
- p = x;
- x = y;
- }
- }
- void bst_morris_postorder(struct bst_node *root)
- {
- struct bst_node dummy;
- struct bst_node *p, *tmp;
- dummy.left = root;
- dummy.right = NULL;
- p = &dummy;
- while (p) {
- if (p->left == NULL) {
- p = p->right;
- }
- else {
- tmp = p->left;
- while (tmp->right != NULL && tmp->right != p)
- tmp = tmp->right;
- if (tmp->right == NULL) {
- tmp->right = p;
- p = p->left;
- }
- else {
- bst_morris_reverse(p->left, tmp);
- tmp->right = NULL;
- p = p->right;
- }
- }
- }
- }
它和中序遍历有所不同,在发现当前结点左子树为空时,不访问此结点(后序遍历需要保证访问完右子树后才能访问根结点),直接访问右子树。
第二次遍历到某个结点时,将该结点左子树的最右路径反序输出即可,对应函数为bst_morris_reverse
转载:http://blog.csdn.net/wdq347/article/details/8853371