中序遍历二叉树 非递归 非栈 用的是指针

有个二叉树,每个节点除了左右指针外,还有一个指向父节点的指针。
要求不用递归,中序遍历这棵树。另要求空间复杂度是O(1).

 

空间复杂度为O(1),摆明就是不让用堆栈模拟递归,所以想了想思路,也请教过好几个朋友,大家都基本想法都差不多,由于有指向父节点的指针,必定可以回溯,从而可以不需要堆栈来做记录.

 

  1. /*思路: 
  2.     关于终止条件:中序遍历终止于最后的rchild,只能先遍历一遍,将该节点作为终止条件。 
  3.     对遍历时候的 cur节点设置一个状态(0,1,2) 
  4.     0标识其左,右节点情况尚未处理 
  5.     1标识其左节点被处理(包括左节点不存在的情况) 
  6.     2标识从右节点返回(包括右节点不存在的情况) 
  7.      
  8.     3种状态的判断用(post->parent->lchild == post)这样的方法判断。 
  9. */  
  10. void inorder_norecursive(LinkTree *root)  
  11. {  
  12.     LinkTree * cur=root, * post, *fin;    
  13.     int cur_state = 0;  
  14.     while(cur != NULL)                //查找终止条件  
  15.     {  
  16.         post = cur;  
  17.         cur = cur->rchild;     
  18.     }  
  19.     fin = post;  
  20.     cur = root;  
  21.     post = NULL;  
  22.     printf("fin data :%d /n",fin->data);  
  23.     while( !(cur == fin && cur_state >=1) )  
  24.     {  
  25.   
  26.         while(cur != NULL && cur->lchild != NULL && cur_state != 2)          //搜索:每次遍历,当前状态清零,找到可以打印的点,从右节点返回不应该继续向下遍历               
  27.         {  
  28.             cur_state = 0;  
  29.             cur = cur->lchild;     
  30.         }  
  31.         if( (cur == NULL && cur_state == 1) ||  cur_state == 2)            //返回:右节点为空,返回的情况或者从右节点返回  
  32.         {  
  33.             cur = post;  
  34.             if(cur->parent->lchild == cur)  
  35.                 cur_state = 1;  
  36.             else if(cur->parent->rchild == cur)  
  37.                 cur_state = 2;  
  38.             cur = cur->parent;  
  39.         }  
  40.         if( cur->lchild == NULL && cur_state == 0)     
  41.             cur_state = 1;  
  42.         post = cur;                             //post针对cur遍历到NULL时候返回,记录有效节点  
  43.         if( cur_state == 1)                     //中序打印  
  44.         {  
  45.             printf(" %d ",cur->data);  
  46.             if(cur == fin)                    //打印最后一个,显式退出  
  47.                 break;  
  48.         }  
  49.         else if(cur_state == 2)                 //节点的2个子节点已被处理,向上返回  
  50.             continue;  
  51.         if(cur->rchild == fin)                //如果是fin节点的父节点,提前设置cur_state状态,防止while退出  
  52.             cur_state = 0;    
  53.         cur = cur->rchild;  
  54.     }     
  55. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值