Chinaunix首页 | 论坛 | 博客
  • 博客访问: 988904
  • 博文数量: 150
  • 博客积分: 3017
  • 博客等级: 少校
  • 技术积分: 3829
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-19 14:40
个人简介

Now in Baidu WISE team

文章分类

全部博文(150)

文章存档

2014年(8)

2013年(31)

2012年(111)

分类: C/C++

2012-12-19 16:45:54

练手代码。参考《王道考研--数据结构》二叉树一章实现。
(未测试)
三种二叉树的遍历的非递归算法基本结构类似:
 
while(node!=NULL && !isEmpty){
       if(node!=NULL){
            //根据算法选取node或其右子树进栈
            node = node->left;
            continue;
       }
       pop(stack,node)
       //根据算法visit及处理右子树
       //后续遍历时需node置空
}
 
Feb.26th 2013 update: add line 71 in DLRN code.

点击(此处)折叠或打开

  1. void LNR(Node* node){
  2.     if(node == NULL) return ;
  3.     LNR(node->left);
  4.     visit(node);
  5.     LNR(node->right;
  6. }

  7. void NLR(Node * node){
  8.     if(node == NULL) return;
  9.     visit(node);
  10.     NLR(node->left);
  11.     NLR(node->right);
  12. }

  13. void LRN(Node * node){
  14.     if(node == NULL) return;
  15.     LRN(node->left);
  16.     LRN(node->right);
  17.     visit(node);
  18. }

  19. void DLNR(Node* node){
  20.     if(node == NULL) return ;
  21.     Stack * stack;
  22.     initialStack(stack);
  23.     while(node!=NULL && !isEmpty(stack)){
  24.         if(node!=NULL){
  25.             push(stack, node);
  26.             node=node->left;
  27.             continue;
  28.         }
  29.         pop(stack,node);
  30.         visit(node);
  31.         node=node->right;
  32.     }
  33. }

  34. void DNLR(Node * node){
  35.     if(node == NULL) return;
  36.     Stack * stack;
  37.     initialStack(stack);
  38.     while(node!=NULL && !isEmpty(stack)){
  39.         if(node!=NULL){
  40.             visit(node);
  41.             if(node->right!=NULL)
  42.                 push(stack, node);
  43.             node=node->left;
  44.             continue;
  45.         }
  46.         pop(stack, node);
  47.         visit(node);
  48.         if(node->right!=NULL)
  49.                 push(stack, node);
  50.         node=node->left;
  51.     }
  52. }

  53. void DLRN(Node *node){
  54.     if(node == NULL) return;
  55.     Stack* stack;
  56.     initialStack(stack);
  57.     Node* lastVisted = NULL;
  58.     while(node!=NULL && !isEmpty(stack)){
  59.         if(node!=NULL){
  60.             push(stack, node);
  61.             node = node->left;
  62.             continue;
  63.         }
  64.         pop(stack, node);
  65.         if(node->right!=NULL && node->right!=lastVisted){
  66.             push(node, stack);
  67.             node = node->right;
  68.             push(node, stack);
  69.             node = node->left;
  70.         }
  71.         else{
  72.             visit(node);
  73.             lastVisited = node;
  74.             node = NULL;
  75.         }
  76.     }

  77. }

阅读(1031) | 评论(1) | 转发(1) |
给主人留下些什么吧!~~

Bean_lee2012-12-24 20:38:36

需要有测试代码。