求一個二叉樹中兩個結點的最大距離

首先說一下距離這個詞,在二叉樹中距離就是從一個節點到另一個結點的邊的條數,爲了更爲清晰的描述這個概念,下面來看一張圖:

這裏寫圖片描述

看上面的圖,藍色線表示的是結點4到6的距離,紅色線表示的是從結點5到6的距離,從圖中我們可以看到,不是所有的距離都經過根結點的,這一點很重要。

那麼怎麼求最遠距離呢?

上面的那個圖中,我們可以很容易看出最遠的距離就是從4到6,或者是從4到5,都是一樣的。而且我們還發現,他們分別是左子樹的最底層的結點和右子樹最底層的結點。那麼我們可不可以這樣算呢,分別求出左子樹和右子樹的高度,然後讓他們相加再加上1(根結點)。

這是最遠的嗎?

顯然不是,下面我們再來看一個例子:

這裏寫圖片描述

如果按照上面我們算的,最遠路徑應該是從2到9,也就是紅色線,但是我們發現,從8到9更長。那麼這裏又有什麼規律呢?
我們在自習看一下這個圖,我們發現不管是哪一條,他們都分別在一個結點的左右子樹中,所以,我們可以將所有的結點的左右子樹的高度和計算一下,然後取出最大值,就是最遠的距離。

接下來看一下這個問題的實現過程:

#include<iostream>
using namespace std;

#include<string>

// 孩子表示法
template<class T>
struct BinaryTreeNode
{
    BinaryTreeNode(const T& value)
    : _value(value)
    , _pLeft(NULL)
    , _pRight(NULL)
    {}

    T _value;
    BinaryTreeNode<T>* _pLeft;   // 左孩子
    BinaryTreeNode<T>* _pRight;  // 右孩子
};

template<class T>
class BinaryTree1
{
    typedef BinaryTreeNode<T> Node;
public:
    BinaryTree1()
        :_pRoot(NULL)
    {}


    BinaryTree1(const T array[], size_t size, const T& invalid)
    {
        size_t index = 0;
        _CreateBinaryTree(_pRoot, array, size, index, invalid);
    }

    //求一個二叉樹中兩個結點的最大距離
    void MaxDistance()
    {
        int _maxlenth = 0;

        //左右子樹中最大深度的和
        cout << _MaxDistance(_pRoot, _maxlenth) << endl;

        cout << _maxlenth << endl;
    }
protected:
    //創建二叉樹
    void _CreateBinaryTree(Node* &pRoot, const T array[], size_t size, size_t& index, const T& invalid)
    {
        if (index < size&&array[index] != invalid)
        {
            pRoot = new Node(invalid);//注意new的時候要和結構體中寫的函數參數對應
            pRoot->_value = array[index];

            _CreateBinaryTree(pRoot->_pLeft, array, size, ++index, invalid);//注意:++index
            _CreateBinaryTree(pRoot->_pRight, array, size, ++index, invalid);
        }
    }

    size_t _MaxDistance(Node* pRoot, int &maxlenth)
    {
        if (pRoot == NULL)
            return 0;

        //左右子樹的長度
        int leftlenth = _MaxDistance(pRoot->_pLeft, maxlenth);
        int rightlenth = _MaxDistance(pRoot->_pRight, maxlenth);

        //用一個臨時變量保存當前的最遠距離,如果大於原來的,那麼交換
        int temp = leftlenth + rightlenth;
        if (temp > maxlenth)
            maxlenth = temp;

        return leftlenth > rightlenth ? leftlenth + 1 : rightlenth + 1;
    }
private:
    Node* _pRoot;
};

void FunTest()
{
    char array[] = "12##3468####5#7#9";
    //char array[] = "124###35##6";
    BinaryTree1<char> bt(array, strlen(array), '#');

    bt.MaxDistance();
}

int main()
{
    FunTest();
    return 0;
}
發佈了121 篇原創文章 · 獲贊 90 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章