二叉树的非递归遍历

用栈实现即可

先序:

  1. void clr(node t[]){
  2.         stack<node*> st;
  3.         node* h = &t[0];
  4.         while(h||!st.empty()){
  5.                 while(h){
  6.                         visit(h->data);
  7.                         st.push(h->rchild);
  8.                         h = h->lchild;
  9.                 }
  10.                 if(!st.empty()){
  11.                         h = st.top();
  12.                         st.pop();
  13.                 }
  14.         }
  15. }

 

中序:

  1. void lcr(node t[]){
  2.         stack<node*> st;
  3.         node* h = &t[0];
  4.         while(h||!st.empty()){
  5.                 while(h){
  6.                         st.push(h);
  7.                         h = h->lchild;
  8.                 }
  9.                 if(!st.empty()){
  10.                         h = st.top();
  11.                         st.pop();
  12.                         visit(h->data);
  13.                         h = h->rchild;
  14.                 }
  15.         }
  16. }

 

后序:

  1. void lrc(node t[]){
  2.         stack<node*> st;
  3.         stack<int> flagst;
  4.         node* h = &t[0];
  5.         int flag = 0;
  6.         while(h||!st.empty()){
  7.                 while(h){
  8.                         st.push(h);
  9.                         flagst.push(0);
  10.                         h = h->lchild;
  11.                 }
  12.                 h = st.top();
  13.                 st.pop();
  14.                 flag = flagst.top();
  15.                 flagst.pop();
  16.                 while(flag){
  17.                         visit(h->data);
  18.                         if(!st.empty()){
  19.                                 h = st.top();
  20.                                 st.pop();
  21.                                 flag = flagst.top();
  22.                                 flagst.pop();
  23.                         }else{
  24.                                 return;
  25.                         }
  26.                 }
  27.                 st.push(h);
  28.                 flagst.push(1);
  29.                 h = h->rchild;
  30.         }
  31. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值