1. 程式人生 > >劍指offer——17.樹的字結構

劍指offer——17.樹的字結構

題目描述:

輸入兩棵二叉樹A,B,判斷B是不是A的子結構。(ps:我們約定空樹不是任意一個樹的子結構)

解題思路:

樹的問題多為遞迴求解,此題重複做多遍有好處。

參考原始碼1:

class Solution
{
        public:
                bool HasSubtree(TreeNode* pRoot1,TreeNode* pRoot2)
                {
                        bool res = false;
                        if(pRoot1 != NULL && pRoot2 != NULL)
                        {
                                if(pRoot1->val == pRoot2->val)  res = Judge(pRoot1,pRoot2);
                                if(!res)  res = HasSubtree(pRoot1->left,pRoot2);
                                if(!res)  res = HasSubtree(pRoot1->right,pRoot2);
                        }
                        return res;
                }
                bool Judge(TreeNode* node1,TreeNode* node2)
                {
                        if(node2 == NULL) return true;
                        if(node1 == NULL) return false;
                        if(node1->val != node2->val) return false;
                        return Judge(node1->left,node2->left) && Judge(node1->right,node2->right);
                }
};

參考原始碼2:

class Solution {
public:
    bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
    {
        if (pRoot1 == NULL || pRoot2 == NULL) return false;
        return isSubtree(pRoot1, pRoot2) || HasSubtree(pRoot1->left, pRoot2)|| HasSubtree(pRoot1->right, pRoot2);
    }
    bool isSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
    {
        if (pRoot2 == NULL) return true;
        if (pRoot1 == NULL) return false;
        if (pRoot1->val != pRoot2->val) return false;
        return isSubtree(pRoot1->left,pRoot2->left) && isSubtree(pRoot1->right, pRoot2->right);
    }
};