二叉树前序遍历、中序遍历、后序遍历的迭代版

二叉树前序遍历、中序遍历、后序遍历的迭代版

  1. 前序遍历
void preorder(TreeNode* root)
{
      if(root==NULL)
           return;
      stack<TreeNode*> s;
      while(root||!s.empty())
      {
              while(root)
              {
                     //...处理root
                     s.push(root);
                     root=root->left;
              } 
              root=s.top();
              s.pop();
              root=root->right; 
      }
}
  1. 中序遍历
void midorder(TreeNode* root)
{
        if(root)
            cout<<"empty!"<<endl;
        stack<int> s;
        while(root||!s.empty())
        {
                while(root)
                {
                	s.push(root);
                	root=root->left; 
                }
                root=s.top();
                s.pop();
                //...处理root
                root=root->right;
        }
}
  1. 后序遍历
void postorder(TreeNode* root) 
{
        stack<TreeNode*> s;
        TreeNode * p = root;
        TreeNode * lastVisited = NULL;//记录上一次访问过的节点
        
        if(p == NULL)
            return ans;
        
        while(!s.empty() || p)
        {
        	//不断往左孩子迭代,直到左孩子为空,同时路径上的节点入栈
            if(p)
            {
                s.push(p);
                p = p->left;
            }
            //此时p==NULL,到达了左下角节点
            else
            {
                p = stk.top();
                //右孩子为空,或者右孩子上次已经访问完
                if(p->right == NULL || p->right == lastVisited)
                {
                    //...处理p
                    lastVisited = p;//更新lastVisited
                    s.pop();
                    p = NULL;
                }
                else{
                    p = p->right;//这时p是第一次被访问,不能直接访问其指向的值,应该先访问右子树
                }
            }
        }
        
        return ans;
    }
	前序遍历和中序遍历基本一样,访问节点位置不一样,后序遍历相对复杂,关键在于lastvisited的追踪。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值