二叉树非递归遍历(C++版本)

本文介绍了二叉树的非递归遍历方法,包括前序遍历、中序遍历和后续遍历,并提供了详细的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


二叉树非递归遍历有三种方式:前序遍历、中序遍历、后续遍历


前序遍历

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode *> s;

        while (root || !s.empty()){
            while (root){
                s.push(root);
                res.push_back(root->val);
                root = root->left;
            }
            root = s.top();
            s.pop();
            root = root->right;
        }
        return res;
    }
};


中序遍历

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode *> s;

        while (root || !s.empty()){
            while (root){
                s.push(root);
                root = root->left;
            }
            root = s.top();
            s.pop();
            res.push_back(root->val);
            root = root->right;
        }

        return res;
    }
};


后续遍历

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode *> s;
        TreeNode * lastNode = NULL, *topNode = NULL;
        while (root || !s.empty()){
            while (root){
                s.push(root);
                root = root->left;
            }
            topNode = s.top();

            // topNode->right != lastNode 表示lastNode 这个节点下面的节点已经遍历过,没有必要再遍历了...
            if (topNode->right != NULL && topNode->right != lastNode){
                root = topNode->right;
            }
            else{
                res.push_back(topNode->val);
                lastNode = topNode;
                s.pop();
            }
        }
        return res;
    }
};





评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值