1. 程式人生 > >二叉樹---前中序陣列建立唯一二叉樹

二叉樹---前中序陣列建立唯一二叉樹

二叉樹的個數

具有n個結點的不同的二叉樹有多少種?這與用棧得出的從1到n的數字有多少種不同的排列具有相同的結論。
那麼,利用給定了一顆二叉樹的前序序列(ABHFDECKG)和中序序列(HBDFAEKCG)能否唯一的確定一顆二叉樹?

前序序列中,第一個字母A一定是數的根結點。中序序列中,被劃分為兩個子序列:((HBDF)A(EKCG)),這樣與二叉樹第一次近似。
然後,取前序序列的下一個字母B,它出現在A的左子樹,應該是A左子樹的根,它把中序子序列又劃分成兩個子序列:((H)B(DF)),A結點的左子樹與二叉樹近似。
通過下面這張圖就可以簡單的理解利用前序序列和中序序列建立二叉樹的過程。

前序序列(A B H F D E C K G)
中序序列(H B D F A E K C G)
這裡寫圖片描述

程式碼實現

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


template<class T>
struct BinTreeNode
{
    BinTreeNode<T> * _pLeft;
    BinTreeNode<T> * _pRight;
    T data;

    BinTreeNode(const T& data = 0 )
        :_pLeft(NULL)
        , _pRight(NULL)
        , data(data)
    {}
};
template
<class T> class BinaryTree { public: //建構函式 BinaryTree() :_pRoot(NULL) {} //利用前序和中序陣列,建立唯一二叉樹 BinTreeNode<T> * CreateBinTree_PreIn(T * VLR, T * LVR, int sz) { if (VLR == NULL || LVR == NULL || sz <= 0) return NULL; int i = 0;//便利中序陣列下標,找到根結點所在位置
while (*VLR != LVR[i]) { i++; } BinTreeNode<T> * t = new BinTreeNode<T>(LVR[i]); t->_pLeft = CreateBinTree_PreIn(VLR + 1, LVR, i); t->_pRight = CreateBinTree_PreIn(VLR + i + 1, LVR + i + 1, sz - i - 1); return t; } //前序遍歷顯示二叉樹 bool preOrder(BinTreeNode<T> * Node) { if (Node == NULL) return false; preOrder(Node->_pLeft); printf("%d", Node->data); preOrder(Node->_pRight); } BinTreeNode<T> * get() { BinTreeNode<T> * ret = _pRoot; return ret; } private: BinTreeNode<T> * _pRoot; }; int main() { BinaryTree<int> s; BinTreeNode<int> * pRoot; int a[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; /*s.CreateBinTree_Queue(a,8); pRoot = s.get(); s.preOrder(pRoot);*/ int VLR[9] = { 1, 2, 4, 8, 9, 5, 3, 6, 7 }; int LVR[9] = { 8, 4, 9, 2, 5, 1, 6, 3, 7 }; pRoot = s.CreateBinTree_PreIn(VLR, LVR, 9); s.preOrder(pRoot); return 0; }