(★★★)二叉树非递归遍历 (统一的解决思路)

转载:【刷题】二叉树非递归遍历

stack<Node*> st;


void preOrder(Node* root) {
    Node *cur = root;
    while (cur || !st.empty()) {
        while (cur) {
            //访问、入栈、转向左孩子
            pre.push_back(cur->data);
            st.push(cur);
            cur = cur->lchild;

        }

        if (!st.empty()) {
            //出栈、转向右孩子
            cur = st.top();
            st.pop();
            cur = cur->rchild;
        }
    }
}

void inOrder(Node* root) {
    Node *cur = root;
    while (cur || !st.empty()) {
        while (cur) {
            //入栈、转向左孩子
            st.push(cur);
            cur = cur->rchild;
        }

        if (!st.empty()) {
            //出栈、访问、转向右孩子
            cur = st.top();
            st.pop();
            in.push_back(cur->data);
            cur = cur->rchild;
        }
    }
}

void postOrder(Node* root) {
    Node *cur = root, *pre = NULL;//pre指向上一个被访问过的节点
    while (cur || !st.empty()) {
        while (cur) {
            //入栈、转向左孩子
            st.push(cur);
            cur = cur->lchild;
        }

        if (!st.empty()) {
            //有条件的出栈,
            cur = st.top();
            // 如果已经访问了右子树,则可以访问根节点;否则转向,先去访问右子树

            if (cur->rchild == NULL || cur->rchild == pre) {
                st.pop();
                post.push_back(cur->data);
                pre = cur;
                cur = NULL;// 表示不需要转向,继续弹栈

            }
            else {
                //转向
                cur = cur->rchild;
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/fuqia/p/9904581.html