C++实现二叉树链表非递归遍历(前序、中序和后序)

#include <iostream>
#include <stack>

struct TreeNode {
    int data;
    TreeNode* left;
    TreeNode* right;

    TreeNode(int val) : data(val), left(nullptr), right(nullptr) {}
};

void iterativePreorder(TreeNode* root) {
    if (root == nullptr) {
        return;
    }

    std::stack<TreeNode*> nodeStack;
    nodeStack.push(root);

    while (!nodeStack.empty()) {
        TreeNode* node = nodeStack.top();
        nodeStack.pop();

        std::cout << node->data << " ";

        if (node->right != nullptr) {
            nodeStack.push(node->right);
        }
        if (node->left != nullptr) {
            nodeStack.push(node->left);
        }
    }
}

void iterativeInorder(TreeNode* root) {
    if (root == nullptr) {
        return;
    }

    std::stack<TreeNode*> nodeStack;
    TreeNode* current = root;

    while (current != nullptr || !nodeStack.empty()) {
        while (current != nullptr) {
            nodeStack.push(current);
            current = current->left;
        }

        current = nodeStack.top();
        nodeStack.pop();
        std::cout << current->data << " ";

        current = current->right;
    }
}

void iterativePostorder(TreeNode* root) {
    if (root == nullptr) {
        return;
    }

    std::stack<TreeNode*> nodeStack1, nodeStack2;
    nodeStack1.push(root);

    while (!nodeStack1.empty()) {
        TreeNode* node = nodeStack1.top();
        nodeStack1.pop();
        nodeStack2.push(node);

        if (node->left != nullptr) {
            nodeStack1.push(node->left);
        }
        if (node->right != nullptr) {
            nodeStack1.push(node->right);
        }
    }

    while (!nodeStack2.empty()) {
        TreeNode* node = nodeStack2.top();
        nodeStack2.pop();
        std::cout << node->data << " ";
    }
}

int main() {
    TreeNode* root = new TreeNode(1);
    root->left = new TreeNode(2);
    root->right = new TreeNode(3);
    root->left->left = new TreeNode(4);
    root->left->right = new TreeNode(5);
    root->right->left = new TreeNode(6);
    root->right->right = new TreeNode(7);

    std::cout << "Iterative Preorder Traversal:" << std::endl;
    iterativePreorder(root);
    std::cout << std::endl;

    std::cout << "Iterative Inorder Traversal:" << std::endl;
    iterativeInorder(root);
    std::cout << std::endl;

    std::cout << "Iterative Postorder Traversal:" << std::endl;
    iterativePostorder(root);
    std::cout << std::endl;

    return 0;
}

我们定义了iterativePreorderiterativeInorderiterativePostorder函数来实现二叉树的非递归前序、中序和后序遍历。在main函数中,我们构建了一个简单的二叉树,并分别调用这三个函数来进行遍历。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值