二叉樹的非遞歸遍歷

二叉樹是一種基礎數據結構,有不少複雜的數據結構是在其基礎上設計的。二叉樹基本的操做包括先序、中序、後序三種遍歷。本文用C++介紹這三種常見遍歷方式的非遞歸實現和二叉樹的層次遍歷。數據結構

二叉樹的結構:spa

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

1、先序遍歷

vector<int> preOrder(TreeNode *root)
{
    vector<int> v;
    stack<TreeNode *> s;
    s.push(root);
    while (!s.empty())
    {
        TreeNode *p = s.top();
        s.pop();
        if (p != 0)
        {
            v.push_back(p->val);
            s.push(p->right);
            s.push(p->left);
        }
    }
    return v;
}

2、中序遍歷

vector<int> preOrder(TreeNode *root)
{
    vector<int> v;
    stack<TreeNode *> s;
    s.push(root);
    while (true)
    {
        while (s.top() != 0)
        {
            s.push(s.top()->left);
        }
        s.pop();
        if (s.empty())
        {
            break;
        }
        TreeNode *p = s.top();
        s.pop();
        v.push_back(p->val);
        s.push(p->right);
    }
    return v;
}

3、後序遍歷

vector<int> preOrder(TreeNode *root)
{
    vector<int> v;
    if (root == 0)
    {
        return v;
    }
    stack<TreeNode *> s;
    TreeNode *p = root;
    do {
        while (p != 0)
        {
            s.push(p);
            p = p->left;
        }
        TreeNode *right = 0;
        while (!s.empty())
        {
            p = s.top();
            if (p->right == right)
            {
                s.pop();
                v.push_back(p->val);
                right = p;
            }
            else
            {
                p = p->right;
                break;
            }
        }
    } while (!s.empty());
    return v;
}

4、層次遍歷

vector<vector<int>> levelOrder(TreeNode* root)
{
    vector<vector<int>> vs;
    if (root == 0) return vs;
    queue<TreeNode *> q;
    q.push(root);
    q.push(0);
    vs.push_back(vector<int>());
    while (!q.empty())
    {
        TreeNode *p = q.front();
        q.pop();
        if (p != 0)
        {
            vs.back().push_back(p->val);
            if (p->left != 0) q.push(p->left);
            if (p->right != 0) q.push(p->right);
        }
        else
        {
            if (q.empty()) break;
            vs.push_back(vector<int>());
            q.push(0);
        }
    }
    return vs;
}
相關文章
相關標籤/搜索