Chinaunix首页 | 论坛 | 博客
  • 博客访问: 268812
  • 博文数量: 84
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 927
  • 用 户 组: 普通用户
  • 注册时间: 2015-03-06 23:00
个人简介

growing

文章分类

全部博文(84)

文章存档

2017年(6)

2016年(61)

2015年(17)

我的朋友

分类: C/C++

2016-03-18 12:20:25

1.前序遍历
利用栈,访问顺序为根,左,右,压栈是先压右,左边后进就可以先访问。

  1. void _PrevOrder_NoR(BinaryTreeNode<T> *root)
  2.     {
  3.         if(root == NULL)
  4.         {
  5.             return;
  6.         }
  7.         stack<BinaryTreeNode<T>*> s;
  8.         s.push(root);
  9.         while(!s.empty())
  10.         {
  11.             BinaryTreeNode<T> *top = s.top();
  12.             s.pop();
  13.             if(top)
  14.             {
  15.                 cout<<top->_data<<" ";
  16.             }
  17.             if(top->_right)
  18.             {
  19.                 s.push(top->_right);
  20.             }
  21.             if(top->_left)
  22.             {
  23.                 s.push(top->_left);
  24.             }
  25.         }
  26.     }
2.中序遍历

  1. void _InOrder_NoR(BinaryTreeNode<T> *root)
  2.     {
  3.         if(root == NULL)
  4.         {
  5.             return;
  6.         }
  7.         stack<BinaryTreeNode<T>*> s;
  8.         BinaryTreeNode<T> *cur = root;
  9.         while(cur || !s.empty())
  10.         {
  11.             if(cur)
  12.             {
  13.                 s.push(cur);
  14.                 cur = cur->_left;
  15.             }
  16.             else
  17.             {
  18.                 cur = s.top();
  19.                 s.pop();
  20.                 cout<<cur->_data<<" ";
  21.                 cur = cur->_right;
  22.             }
  23.         }
  24.     }





3.后序遍历
从左上到右下斜着遍历的。依然利用栈。

  1. void _PostOrder_NoR(BinaryTreeNode<T> *root)
  2.     {
  3.         if(root == NULL)
  4.         {
  5.             return;
  6.         }
  7.         stack<BinaryTreeNode<T>*> s;
  8.         BinaryTreeNode<T> *cur = root;
  9.         BinaryTreeNode<T> *PreVisited = NULL;
  10.         while(cur)
  11.         {
  12.             s.push(cur);
  13.             cur = cur->_left;
  14.         }
  15.         while(!s.empty())
  16.         {
  17.             BinaryTreeNode<T> *top = s.top();
  18.             s.pop();
  19.             //根节点想要被访问,必须右孩子被访问过,或者没有有孩子
  20.             if(top->_right == NULL || PreVisited == top->_right)
  21.             {
  22.                 cout<<top->_data<<" ";
  23.                 PreVisited = top;
  24.             }
  25.             else
  26.             {
  27.                 s.push(top);
  28.                 top = top->_right;
  29.                 while(top)
  30.                 {
  31.                     s.push(top);
  32.                     top = top->_left;
  33.                 }
  34.             }
  35.         }
  36.     }


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