劍指 offer 判斷一棵樹是否包含另一棵樹

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

 

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