算法基础 - 非递归使用栈遍历树

一直觉得非递归遍历树也很简单,就一直没有写,小问题栽了大跟头啊,继续努力吧。

这里说一下非递归的思想主要是怎么做,使用栈空间和使用递归比较像,但是有一些细节不一样,因为while循环可能在后序遍历的时候重复压栈。

下面写一下三种遍历的代码:

  1. 先序遍历
void preorderTree(TreeNode * root){
    stack<TreeNode *> st;
    TreeNode * temp = root;
    while (temp != NULL || !st.empty()) {
        while (temp != NULL) {//每次把左子树全部压进去
            st.push(temp);
            cout<<st.top()->val<<endl;//压栈的时候就输出
            temp = temp->left;
        }
        if (!st.empty()) {//左子树已经压完了 找到右子树
            temp = st.top()->right;//输出完找到右孩子
            st.pop();
        }
    }
}
  1. 中序遍历
void inorderTree(TreeNode * root){
    stack<TreeNode *> st;
    TreeNode * temp = root;
    while (temp != NULL || !st.empty()) {
        while (temp != NULL) {
            st.push(temp);
            temp = temp->left;
        }
        if (!st.empty()) {
            cout<<st.top()->val<<endl;
            temp = st.top()->right;
            st.pop();
        }
    }
}
  1. 后序遍历
void nextorderTree(TreeNode * root){
    stack<TreeNode *> st;
    TreeNode * temp = root;
    while (temp != NULL || !st.empty()) {
        while (temp != NULL) {
            st.push(temp);
            if (temp->left == NULL) {
                temp = temp->right;
            }else{
                temp = temp->left;
            }
        }
        while (!st.empty() && temp == st.top()->right) {
            temp = st.top();
            cout<<temp->val<<endl;
            st.pop();
        }
        if (!st.empty()) {
            temp = st.top()->right;
        }else{
            temp = NULL;
        }
    }
}

这里主要解释一下后序遍历,压栈的时候,我把左子树和右子树全部都压到栈里了。这个时候先左后右再中间,那么遇到一个问题,就是弹栈的时候,如果只弹了一次,可能会出现while循环会再次压右子树的情况,所以一次把栈里面所有右节点都弹出来,直到判断到弹出的元素是栈顶元素的左孩子为止。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值