您的位置:首页 > 其它

不使用递归和栈实现二叉树的中序遍历

2015-07-06 17:45 447 查看
不使用递归和栈实现二叉树的中序遍历

总体思路:

主要问题:不使用递归及栈,就无法回到当前节点的父节点。

解决办法:

1.在每一个节点中添加一个指向父节点的的指针

2.让以下一个节点为根的树的最右节点指向当前节点。

下面是第二种方法的代码及解析。

节点指针图片示意:



源代码如下(C语言实现)

源码出处:http://www.acmerblog.com/inorder-tree-traversal-without-recursion-and-without-stack-5988.html

[code]#include<stdio.h>
#include<stdlib.h>

struct tNode
{
   int data;
   struct tNode* left;
   struct tNode* right;
};

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
    {
      /* 找到current的前驱节点 */
      pre = current->left;
      while(pre->right != NULL && pre->right != current)
        pre = pre->right;

      /* 将current节点作为其前驱节点的右孩子 */
      if(pre->right == NULL)
      {
        pre->right = current;
        current = current->left;
      }

      /* 恢复树的原有结构,更改right 指针 */   
      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 */
}

struct tNode* newtNode(int data)
{
  struct tNode* tNode = (struct tNode*)
                       malloc(sizeof(struct tNode));
  tNode->data = data;
  tNode->left = NULL;
  tNode->right = NULL;

  return(tNode);
}

/* 测试*/
int main()
{

  /* 构建树结构如下:
            1
          /   \
        2      3
      /  \
    4     5
  */
  struct tNode *root = newtNode(1);
  root->left        = newtNode(2);
  root->right       = newtNode(3);
  root->left->left  = newtNode(4);
  root->left->right = newtNode(5); 

  MorrisTraversal(root);
   return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: