二叉樹的遍歷方法總結與c++實現

概述:

二叉樹的遍歷方式分爲:
深度遍歷(前序,中序,後序)
廣度遍歷(層次遍歷)

二叉樹是一種非常重要的數據結構,很多其它數據結構都是基於二叉樹的基礎演變而來的。對於二叉樹,有深度遍歷和廣度遍歷,深度遍歷有前序、中序以及後序三種遍歷方法,廣度遍歷即我們平常所說的層次遍歷。因爲樹的定義本身就是遞歸定義,因此採用遞歸的方法去實現樹的三種遍歷不僅容易理解而且代碼很簡潔,而對於廣度遍歷來說,需要其他數據結構的支撐,比如堆了。所以,對於一段代碼來說,可讀性有時候要比代碼本身的效率要重要的多。

四種主要的遍歷思想爲:

前序遍歷:根結點 ---> 左子樹 ---> 右子樹   (此處所謂的根節點是以當前點作爲根節點,並不是指整個二叉樹的根節點)

中序遍歷:左子樹---> 根結點 ---> 右子樹     (此處所謂的根節點是以當前點作爲根節點,並不是指整個二叉樹的根節點)

後序遍歷:左子樹 ---> 右子樹 ---> 根結點    (此處所謂的根節點是以當前點作爲根節點,並不是指整個二叉樹的根節點)

層次遍歷:只需按層次遍歷即可

 

例如,求下面二叉樹的各種遍歷

前序遍歷:1  2  4  5  7  8  3  6 

中序遍歷:4  2  7  5  8  1  3  6

後序遍歷:4  7  8  5  2  6  3  1

層次遍歷:1  2  3  4  5  6  7  8


 

c++實現遍歷方法:

BSTree.h

/**
 * C++ 語言: 二叉查找樹
 *
 * @author skywang
 * @date 2013/11/07
 */

#ifndef _BINARY_SEARCH_TREE_HPP_
#define _BINARY_SEARCH_TREE_HPP_

#include <iomanip>
#include <iostream>
using namespace std;

template <class T>
class BSTNode{
    public:
        T key;            // 關鍵字(鍵值)
        BSTNode *left;    // 左孩子
        BSTNode *right;    // 右孩子
        BSTNode *parent;// 父結點

        BSTNode(T value, BSTNode *p, BSTNode *l, BSTNode *r):
            key(value),parent(),left(l),right(r) {}
};

template <class T>
class BSTree {
    private:
        BSTNode<T> *mRoot;    // 根結點

    public:
        BSTree();
        ~BSTree();

        // 前序遍歷"二叉樹"
        void preOrder();
        // 中序遍歷"二叉樹"
        void inOrder();
        // 後序遍歷"二叉樹"
        void postOrder();

        // (遞歸實現)查找"二叉樹"中鍵值爲key的節點
        BSTNode<T>* search(T key);
        // (非遞歸實現)查找"二叉樹"中鍵值爲key的節點
        BSTNode<T>* iterativeSearch(T key);

        // 查找最小結點:返回最小結點的鍵值。
        T minimum();
        // 查找最大結點:返回最大結點的鍵值。
        T maximum();

        // 找結點(x)的後繼結點。即,查找"二叉樹中數據值大於該結點"的"最小結點"。
        BSTNode<T>* successor(BSTNode<T> *x);
        // 找結點(x)的前驅結點。即,查找"二叉樹中數據值小於該結點"的"最大結點"。
        BSTNode<T>* predecessor(BSTNode<T> *x);

        // 將結點(key爲節點鍵值)插入到二叉樹中
        void insert(T key);

        // 刪除結點(key爲節點鍵值)
        void remove(T key);

        // 銷燬二叉樹
        void destroy();

        // 打印二叉樹
        void print();
    private:
        // 前序遍歷"二叉樹"
        void preOrder(BSTNode<T>* tree) const;
        // 中序遍歷"二叉樹"
        void inOrder(BSTNode<T>* tree) const;
        // 後序遍歷"二叉樹"
        void postOrder(BSTNode<T>* tree) const;

        // (遞歸實現)查找"二叉樹x"中鍵值爲key的節點
        BSTNode<T>* search(BSTNode<T>* x, T key) const;
        // (非遞歸實現)查找"二叉樹x"中鍵值爲key的節點
        BSTNode<T>* iterativeSearch(BSTNode<T>* x, T key) const;

        // 查找最小結點:返回tree爲根結點的二叉樹的最小結點。
        BSTNode<T>* minimum(BSTNode<T>* tree);
        // 查找最大結點:返回tree爲根結點的二叉樹的最大結點。
        BSTNode<T>* maximum(BSTNode<T>* tree);

        // 將結點(z)插入到二叉樹(tree)中
        void insert(BSTNode<T>* &tree, BSTNode<T>* z);

        // 刪除二叉樹(tree)中的結點(z),並返回被刪除的結點
        BSTNode<T>* remove(BSTNode<T>* &tree, BSTNode<T> *z);

        // 銷燬二叉樹
        void destroy(BSTNode<T>* &tree);

        // 打印二叉樹
        void print(BSTNode<T>* tree, T key, int direction);
};

/*
 * 構造函數
 */
template <class T>
BSTree<T>::BSTree():mRoot(NULL)
{
}

/*
 * 析構函數
 */
template <class T>
BSTree<T>::~BSTree()
{
    destroy();
}

/*
 * 前序遍歷"二叉樹"
 */
template <class T>
void BSTree<T>::preOrder(BSTNode<T>* tree) const
{
    if(tree != NULL)
    {
        cout<< tree->key << " " ;
        preOrder(tree->left);
        preOrder(tree->right);
    }
}

template <class T>
void BSTree<T>::preOrder()
{
    preOrder(mRoot);
}

/*
 * 中序遍歷"二叉樹"
 */
template <class T>
void BSTree<T>::inOrder(BSTNode<T>* tree) const
{
    if(tree != NULL)
    {
        inOrder(tree->left);
        cout<< tree->key << " " ;
        inOrder(tree->right);
    }
}

template <class T>
void BSTree<T>::inOrder()
{
    inOrder(mRoot);
}

/*
 * 後序遍歷"二叉樹"
 */
template <class T>
void BSTree<T>::postOrder(BSTNode<T>* tree) const
{
    if(tree != NULL)
    {
        postOrder(tree->left);
        postOrder(tree->right);
        cout<< tree->key << " " ;
    }
}

template <class T>
void BSTree<T>::postOrder()
{
    postOrder(mRoot);
}

/*
 * (遞歸實現)查找"二叉樹x"中鍵值爲key的節點
 */
template <class T>
BSTNode<T>* BSTree<T>::search(BSTNode<T>* x, T key) const
{
    if (x==NULL || x->key==key)
        return x;

    if (key < x->key)
        return search(x->left, key);
    else
        return search(x->right, key);
}

template <class T>
BSTNode<T>* BSTree<T>::search(T key)
{
    search(mRoot, key);
}

/*
 * (非遞歸實現)查找"二叉樹x"中鍵值爲key的節點
 */
template <class T>
BSTNode<T>* BSTree<T>::iterativeSearch(BSTNode<T>* x, T key) const
{
    while ((x!=NULL) && (x->key!=key))
    {
        if (key < x->key)
            x = x->left;
        else
            x = x->right;
    }

    return x;
}

template <class T>
BSTNode<T>* BSTree<T>::iterativeSearch(T key)
{
    iterativeSearch(mRoot, key);
}

/*
 * 查找最小結點:返回tree爲根結點的二叉樹的最小結點。
 */
template <class T>
BSTNode<T>* BSTree<T>::minimum(BSTNode<T>* tree)
{
    if (tree == NULL)
        return NULL;

    while(tree->left != NULL)
        tree = tree->left;
    return tree;
}

template <class T>
T BSTree<T>::minimum()
{
    BSTNode<T> *p = minimum(mRoot);
    if (p != NULL)
        return p->key;

    return (T)NULL;
}

/*
 * 查找最大結點:返回tree爲根結點的二叉樹的最大結點。
 */
template <class T>
BSTNode<T>* BSTree<T>::maximum(BSTNode<T>* tree)
{
    if (tree == NULL)
        return NULL;

    while(tree->right != NULL)
        tree = tree->right;
    return tree;
}

template <class T>
T BSTree<T>::maximum()
{
    BSTNode<T> *p = maximum(mRoot);
    if (p != NULL)
        return p->key;

    return (T)NULL;
}

/*
 * 找結點(x)的後繼結點。即,查找"二叉樹中數據值大於該結點"的"最小結點"。
 */
template <class T>
BSTNode<T>* BSTree<T>::successor(BSTNode<T> *x)
{
    // 如果x存在右孩子,則"x的後繼結點"爲 "以其右孩子爲根的子樹的最小結點"。
    if (x->right != NULL)
        return minimum(x->right);

    // 如果x沒有右孩子。則x有以下兩種可能:
    // (01) x是"一個左孩子",則"x的後繼結點"爲 "它的父結點"。
    // (02) x是"一個右孩子",則查找"x的最低的父結點,並且該父結點要具有左孩子",找到的這個"最低的父結點"就是"x的後繼結點"。
    BSTNode<T>* y = x->parent;
    while ((y!=NULL) && (x==y->right))
    {
        x = y;
        y = y->parent;
    }

    return y;
}

/*
 * 找結點(x)的前驅結點。即,查找"二叉樹中數據值小於該結點"的"最大結點"。
 */
template <class T>
BSTNode<T>* BSTree<T>::predecessor(BSTNode<T> *x)
{
    // 如果x存在左孩子,則"x的前驅結點"爲 "以其左孩子爲根的子樹的最大結點"。
    if (x->left != NULL)
        return maximum(x->left);

    // 如果x沒有左孩子。則x有以下兩種可能:
    // (01) x是"一個右孩子",則"x的前驅結點"爲 "它的父結點"。
    // (01) x是"一個左孩子",則查找"x的最低的父結點,並且該父結點要具有右孩子",找到的這個"最低的父結點"就是"x的前驅結點"。
    BSTNode<T>* y = x->parent;
    while ((y!=NULL) && (x==y->left))
    {
        x = y;
        y = y->parent;
    }

    return y;
}

/*
 * 將結點插入到二叉樹中
 *
 * 參數說明:
 *     tree 二叉樹的根結點
 *     z 插入的結點
 */
template <class T>
void BSTree<T>::insert(BSTNode<T>* &tree, BSTNode<T>* z)
{
    BSTNode<T> *y = NULL;
    BSTNode<T> *x = tree;

    // 查找z的插入位置
    while (x != NULL)
    {
        y = x;
        if (z->key < x->key)
            x = x->left;
        else
            x = x->right;
    }

    z->parent = y;
    if (y==NULL)
        tree = z;
    else if (z->key < y->key)
        y->left = z;
    else
        y->right = z;
}

/*
 * 將結點(key爲節點鍵值)插入到二叉樹中
 *
 * 參數說明:
 *     tree 二叉樹的根結點
 *     key 插入結點的鍵值
 */
template <class T>
void BSTree<T>::insert(T key)
{
    BSTNode<T> *z=NULL;

    // 如果新建結點失敗,則返回。
    if ((z=new BSTNode<T>(key,NULL,NULL,NULL)) == NULL)
        return ;

    insert(mRoot, z);
}

/*
 * 刪除結點(z),並返回被刪除的結點
 *
 * 參數說明:
 *     tree 二叉樹的根結點
 *     z 刪除的結點
 */
template <class T>
BSTNode<T>* BSTree<T>::remove(BSTNode<T>* &tree, BSTNode<T> *z)
{
    BSTNode<T> *x=NULL;
    BSTNode<T> *y=NULL;

    if ((z->left == NULL) || (z->right == NULL) )
        y = z;
    else
        y = successor(z);

    if (y->left != NULL)
        x = y->left;
    else
        x = y->right;

    if (x != NULL)
        x->parent = y->parent;

    if (y->parent == NULL)
        tree = x;
    else if (y == y->parent->left)
        y->parent->left = x;
    else
        y->parent->right = x;

    if (y != z)
        z->key = y->key;

    return y;
}

/*
 * 刪除結點(z),並返回被刪除的結點
 *
 * 參數說明:
 *     tree 二叉樹的根結點
 *     z 刪除的結點
 */
template <class T>
void BSTree<T>::remove(T key)
{
    BSTNode<T> *z, *node;

    if ((z = search(mRoot, key)) != NULL)
        if ( (node = remove(mRoot, z)) != NULL)
            delete node;
}

/*
 * 銷燬二叉樹
 */
template <class T>
void BSTree<T>::destroy(BSTNode<T>* &tree)
{
    if (tree==NULL)
        return ;

    if (tree->left != NULL)
        return destroy(tree->left);
    if (tree->right != NULL)
        return destroy(tree->right);

    delete tree;
    tree=NULL;
}

template <class T>
void BSTree<T>::destroy()
{
    destroy(mRoot);
}

/*
 * 打印"二叉查找樹"
 *
 * key        -- 節點的鍵值
 * direction  --  0,表示該節點是根節點;
 *               -1,表示該節點是它的父結點的左孩子;
 *                1,表示該節點是它的父結點的右孩子。
 */
template <class T>
void BSTree<T>::print(BSTNode<T>* tree, T key, int direction)
{
    if(tree != NULL)
    {
        if(direction==0)    // tree是根節點
            cout << setw(2) << tree->key << " is root" << endl;
        else                // tree是分支節點
            cout << setw(2) << tree->key << " is " << setw(2) << key << "'s "  << setw(12) << (direction==1?"right child" : "left child") << endl;

        print(tree->left, tree->key, -1);
        print(tree->right,tree->key,  1);
    }
}

template <class T>
void BSTree<T>::print()
{
    if (mRoot != NULL)
        print(mRoot, mRoot->key, 0);
}

#endif

main.cpp

/**
 * C++ 語言: 二叉查找樹
 *
 * @author skywang
 * @date 2013/11/07
 */

#include <iostream>
#include "BSTree.h"
using namespace std;

static int arr[]= {1,5,4,3,2,6};
#define TBL_SIZE(a) ( (sizeof(a)) / (sizeof(a[0])) )

int main()
{
    int i, ilen;
    BSTree<int>* tree=new BSTree<int>();

    cout << "== 依次添加: ";
    ilen = TBL_SIZE(arr);
    for(i=0; i<ilen; i++)
    {
        cout << arr[i] <<" ";
        tree->insert(arr[i]);
    }

    cout << "\n== 前序遍歷: ";
    tree->preOrder();

    cout << "\n== 中序遍歷: ";
    tree->inOrder();

    cout << "\n== 後序遍歷: ";
    tree->postOrder();
    cout << endl;

    cout << "== 最小值: " << tree->minimum() << endl;
    cout << "== 最大值: " << tree->maximum() << endl;
    cout << "== 樹的詳細信息: " << endl;
    tree->print();

    cout << "\n== 刪除根節點: " << arr[3];
    tree->remove(arr[3]);

    cout << "\n== 中序遍歷: ";
    tree->inOrder();
    cout << endl;

    // 銷燬二叉樹
    tree->destroy();

    return 0;
}

參考文章:https://www.cnblogs.com/skywang12345/p/3576373.html

https://blog.csdn.net/My_Jobs/article/details/43451187

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章