二叉树遍历的非递归总结

          本文主要总结先序,中序,后序的非递归,基本思路都是用stack进行

先序的非递归,两种写法,一种是注意加入左右孩子时判断是否为空,主要注意先加入右孩子保证左孩子先出来

void preOrderIter(TreeNode *root)
{
    if (root == nullptr) return;
    stack<TreeNode *> s;
    s.push(root);
    while (!s.empty()) {
        TreeNode *nd = s.top();
        ans.push_back(nd->val);
        s.pop();
        if (nd->right)
            s.push(nd->right);
        if (nd->left)
            s.push(nd->left);
    }
    
}

另一种写法,一直访问左孩子直到空访问右孩子

void preOrderIter2(TreeNode *root)
{
    stack<TreeNode *> s;
    while (root || !s.empty()) {
        if (root) {
           ans.push_back(root->val);
            s.push(root);              
            root = root->left;         //访问左子树
        } else {
            root = s.top();            //回溯至父亲结点
            s.pop();
            root = root->right;        //访问右子树
        }
    }
 
}

 中序遍历:

void inOrderIter(TreeNode *root)
{
    stack<TreeNode *> s;
    while (root != NULL || !s.empty()) {
        if (root != NULL) {
            s.push(root);
            root = root->left;
        }
        else {
            root = s.top();
            ans.push_back(root->val);
            s.pop();
            root = root->right;        //访问右子树
        }
    }
    
}

后序遍历:

void postOrderIter(TreeNode *root)
{
    if (!root) return;
    stack<TreeNode*> s;
    s.push(root);
    while (!s.empty()) {
        TreeNode *curr = s.top();
        ans.push(curr);
        s.pop();
        if (curr->left)
            s.push(curr->left);
        if (curr->right)
            s.push(curr->right);
    }
    reverse(ans.begin(),ans.end());
   
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值