二叉树遍历非递归写法c++

参考博客:二叉树的递归和非递归方式的三种遍历

1、前序遍历

/*
将根节点压栈,(栈先进后出)
然后对于栈顶节点,先输出栈顶节点的值,
然后把右孩子压栈,再把左孩子压栈。
对应于先序遍历的先遍历父节点,再遍历左节点再遍历右节点的顺序
*/
void preOrderRecursion(treeNode* root) {
        if (!root) {
            cout << "empty tree!\n";
            return;
        }
        stack<treeNode*> s;
        s.push(root);
        while (!s.empty()) {
            treeNode* temp = s.top();
            s.pop();
            cout << temp->value << " ";
            if (temp->right)
                s.push(temp->right);
            if (temp->left)
                s.push(temp->left);
        }
    }

2、中序遍历

/*
初始节点为根节点,
若节点不为空,
则将当前节点压栈,节点替换为节点的左孩子;
否则输出栈顶元素的值,
当前节点替换为栈顶元素的右孩子,出栈。
对应于中序遍历的先遍历左孩子,再遍历父节点,再遍历右孩子
*/
void inOrderRecursion(treeNode* root) {
        if (!root) {
            cout << "empty tree!\n";
            return;
        }
        stack<treeNode*> s;
        while (!s.empty() || root) {
            if (root) {
                s.push(root);
                root = root->left;
            } else {
                treeNode* current = s.top();
                s.pop();
                cout << current->value << " ";
                root = current->right;
            }
        }
    }

3、后序遍历

/*
由两个栈实现,
先把根节点压入第一个栈,
当栈1不为空时,
出栈,并压入第二个栈,然后将刚才出栈的栈顶元素的左右孩子入栈1;
然后打印出栈2内的元素
对应于后序遍历的先遍历左右孩子再遍历父节点
*/
void postOrderRecursion(treeNode* root) {
        if (!root) {
            cout << "empty tree!\n";
            return;
        }
        stack<treeNode*> s1, s2;
        s1.push(root);
        while (!s1.empty()) {
            treeNode* current = s1.top();
            s1.pop();
            s2.push(current);
            if (current->left) s1.push(current->left);
            if (current->right) s1.push(current->right);
        }
        while (!s2.empty()) {
            treeNode* top = s2.top();
            s2.pop();
            cout << top->value << " ";
        }
    }

猜你喜欢

转载自blog.csdn.net/unirrrrr/article/details/81192033