1. 程式人生 > >前序後序中序遍歷非遞迴實現

前序後序中序遍歷非遞迴實現

前序非遞迴實現

void pre_show2() {
        if (root == 0)
            return;
        stack<Node<T> * > con;
        Node<T>* t = root;
        con.push(t);
        while (!con.empty()) {
            cout << t->data << " ";
            if (t->right)
                con.push(t->right);
            if
(t->left) t = t->left; else { t = con.top(); con.pop(); } } cout << endl; }

中序非遞迴實現

void in_show2()
    {
        if (root == 0 )
            return;
        stack<Node<T>*> q;
        Node<T>* p = root;
        while
(!q.empty() || p) { if (p) { q.push(p); p = p->left; } else { p = q.top(); q.pop(); cout << p->data << " "; p = p->right; } } cout << endl; }

後序非遞迴實現

void post_show2() {
        if (root == 0)
            return;
        stack<Node<T>*> q;
        Node<T>* t = root;
        Node<T>* last_visit = 0;
        while (t) {
            q.push(t);
            t = t->left;
        }
        while (!q.empty()) {
            t  = q.top(); q.pop();
            if (t->right == 0 || last_visit == t->right)
            {   //如果是葉子或者一個節點的右孩子已經訪問過了輸出該節點的data值
                cout << t -> data << " ";
                last_visit = t;
            } else {
                q.push(t);
                t = t->right;       //進入右孩子
                while(t){
                    q.push(t);
                    t = t->left;
                }
            }
        }
        cout <<endl;
    }