设为首页 加入收藏

TOP

算法----二叉树Morris中序遍历
2014-02-14 12:51:14 来源: 作者: 【 】 浏览:127
Tags:算法 ---- Morris

  无论是二叉树的中序遍历还是用 stack 模拟递归, 都需要 O(n)的空间复杂度。

  Morris 遍历是一种 常数空间 的遍历方法,其本质是 线索二叉树(Threaded Binary Tree), 本质上其实就是利用二叉树中 n+1 个指向NULL的指针。

  Morris 遍历在遍历的过程中,通过利用叶子节点空的right指针,指向中序遍历的下一个节点,从而避免了对 stack 的依赖。

  // Morris Traversal

  // space effienct

  void InOrderVisitMorris(TreeNode *root)

  {

  TreeNode *pre(NULL);

  while(root)

  {

  // 左子树是空,直接访问该节点,然后访问右子树

  if(root->left_child == NULL){

  cout << root->value << " ";

  root = root->right_child;

  continue;

  }

  // 找 root 的前驱节点

  for(pre = root->left_child; pre->right_child && pre->right_child != root; pre = pre->right_child);

  // 第一次访问root, 建立线索

  if(pre->right_child == NULL){

  pre->right_child = root;

  root = root->left_child;

  }

  // 第二次访问,说明左子树已经访问过

  else{

  pre->right_child = NULL;

  cout << root->value << " ";

  root = root->right_child;

  }

  }

  }

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇C++创建对象的两种方法 下一篇C++ 之函数模版

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Libevent C++ 高并发 (2025-12-26 00:49:30)
·C++ dll 设计接口时 (2025-12-26 00:49:28)
·透彻理解 C 语言指针 (2025-12-26 00:22:52)
·C语言指针详解 (经典 (2025-12-26 00:22:49)
·C 指针 | 菜鸟教程 (2025-12-26 00:22:46)