极其优雅的二叉树非递归后序遍历

187 阅读1分钟

复习的时候发现了一种极其优雅的二叉树后序遍历算法,思想如下:

    1. 将根节点压入第一个栈
    1. 从第一个栈中弹出一个元素,压入第二个栈
    1. 然后分别将该节点的左右孩子压入第一个栈
  • 4.重复步骤2和步骤3直到第一个栈为空

执行结束,第二个栈中就保存了所有节点的后序遍历输出结果。依次将元素从第二个栈中弹出即可。

代码如下:


void btree::postOrderTraverseIteration(treeNode *root) {
    stack<treeNode *> first, second;
    if (!root) {
        return;
    } else {
        first.push(root);
        while (!first.empty()) {
            auto item = first.top();
            second.push(item);
            first.pop();
            item = second.top();
            if (item->lChild) {
                first.push(item->lChild);
            }
            if (item->rChild) {
                first.push(item->rChild);
            }
        }

        while (!second.empty()) {
            cout << second.top()->data;
            second.pop();
        }
    }
}