使用迭代實現二叉樹的前中後序遍歷(C++)

使用遞歸實現二叉樹的前中後序遍歷很簡單,寫法基本相同。但用迭代稍有不同,較遞歸稍難理解和記憶,但迭代效率更高。下面是用迭代實現二叉樹的前中後序遍歷的代碼示例。

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

//Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

/*
         7
        / \
       4   8
      /    /
     9    34
*/


/*使用迭代實現二叉樹的前後中序遍歷*/

//前序遍歷
vector<int> preOrder(TreeNode* root) {
    vector<int> res;
    if (root == NULL) {
        return res;
    }
    stack<TreeNode*> st;
    st.push(root);
    while (st.size()) {
        TreeNode* p = st.top();
        st.pop();
        res.push_back(p->val);
        if (p->right) {
            st.push(p->right);
        }
        if (p->left) {
            st.push(p->left);
        }
    }
    return res;
}

//後序遍歷
//後序遍歷是:左右根,前序遍歷是:跟左右,可以先將前序遍歷換成跟右左,就和前序遍歷一樣了
vector<int> subOrder(TreeNode* root) {
    vector<int> res;
    if (root == NULL) {
        return res;
    }
    stack<TreeNode*> st;
    st.push(root);
    while (st.size() > 0) {
        TreeNode* p = st.top();
        st.pop();
        res.push_back(p->val);
        if (p->left) {
            st.push(p->left);
        }
        if (p->right) {
            st.push(p->right);
        }
    }
    reverse(res.begin(), res.end());
    return res;
}

//中序遍歷
vector<int> inOrder(TreeNode* root) {
    vector<int> res;
    if (root == NULL) {
        return res;
    }
    stack<TreeNode*> st;
    TreeNode* p = root;

    while (st.size() > 0 || p != NULL) {
        while (p != NULL) {
            st.push(p);
            p = p->left;
        }

        if (st.size() > 0) {
            p = st.top();
            st.pop();
            res.push_back(p->val);
            p = p->right;
        }
    }
    return res;
}

void PrintVector(vector<int> vec) {
    int n = vec.size();
    for (int i = 0; i < n; i++) {
        cout << vec[i] << "\t";
    }
    cout << endl;
}

int main()
{
    TreeNode n1(7);
    TreeNode n2(4);
    TreeNode n3(8);
    TreeNode n4(9);
    TreeNode n5(34);
    n1.left = &n2;
    n1.right = &n3;
    n2.left = &n4;
    n3.left = &n5;

    vector<int> res = preOrder(&n1);
    cout << "前序遍歷爲:" << endl; 
    PrintVector(res);

    vector<int> res2 = subOrder(&n1);
    cout << "後序遍歷爲:" << endl;
    PrintVector(res2);

    vector<int> res3 = inOrder(&n1);
    cout << "中序遍歷爲:" << endl;
    PrintVector(res3);
    
}

 

發佈了37 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章