樹的子結構,子結構

來源:互聯網
上載者:User

樹的子結構,子結構

1. 題目

輸入兩棵二叉樹A和B,判斷B是不是A的子結構。二叉樹定義結構如下:

struct BinaryTreeNode

{

      int m_nValue;

           BinaryTreeNode*m_pLeft;

           BinaryTreeNOde*m_pRight;

};

例1-1(a)中紅色部分和(b)的結構相同:對應位置資料域相同。

圖1-1樹的子結構

2. 分析


顯然易得樹A中存在一個結點pRoot1與樹B的根結點pRoot2滿足以下關係時B是A的子結構:

    (1) pRoot1與pRoot2值相同;

    (2) pRoot1的左子樹與pRoot2左子樹結構完全相同;

    (3) pRoot1的右子樹與pRoot2右子樹結構完全相同。

3. 實現方法

方法一:

通過遞迴遍曆樹求得結果,時間複雜度O(m*n),其中m、n分別為A與B中結點個數。

方法二:

(1) 以先序遍曆樹A與B得到兩個遍曆序列Apre與Bpre。

(2) 以後序遍曆樹A與B得到兩個遍曆序列Apast與Bpast。

(3) 用字串比較演算法KMP分別檢測,若Apre包含Bpre且Apast包含Bpast則B是A的子結構,反之不是。

該方法時間複雜度O(m+n),其中m、n分別為A與B中結點個數。

注意:因為一個遍曆順序無法唯一的確定一棵二叉樹,因此需要兩個遍曆順序。


4. 代碼

代碼中認為兩棵樹均為空白時B不是A的子結構。

boolHasSubtree(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2){    bool result = false;     if(pRoot1 != NULL && pRoot2 !=NULL)    {        if(pRoot1->m_nValue ==pRoot2->m_nValue)            result = DoesTree1HaveTree2(pRoot1,pRoot2);        if(!result)            result =HasSubtree(pRoot1->m_pLeft, pRoot2);        if(!result)            result = HasSubtree(pRoot1->m_pRight,pRoot2);    }     return result;} boolDoesTree1HaveTree2(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2){    if(pRoot2 == NULL)        return true;     if(pRoot1 == NULL)        return false;     if(pRoot1->m_nValue != pRoot2->m_nValue)        return false;     return DoesTree1HaveTree2(pRoot1->m_pLeft, pRoot2->m_pLeft) && DoesTree1HaveTree2(pRoot1->m_pRight,pRoot2->m_pRight);}

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.