Offer- prove safety substructure face questions 26- tree - binary

/ * 
Title: 
	input two binary A and B, B is determined to not A subtree. 
* / 
/ * 
Ideas: 
	1, note that the size of the float is determined. 
	2, if a root node of the tree determination tree A and B are the same, 
		if the same, it is judged as the root node to node A contains the tree B; 
		if not contained, it is determined whether the left subtree A tree comprising B ; 
		if comprising determining right subtree a tree contains B. 
	3, a node A is a root, the root node determines whether the corresponding B, and 
		determines equality left subtree left subtree of A and B; A determination equality right subtree right subtree and B .	
* / 
#Include <the iostream> 
#include <the cstdlib> 

the using namespace STD; 

struct the TreeNode { 
	int Val; 
	struct the TreeNode * left; 
	struct the TreeNode * right; 
	the TreeNode (int X): 
			Val (X), left (NULL), right ( NULL) { 
	} 
}; 
 
BOOL the equals (Double num1, Double num2) {
    IF (num1-num2> -0.0000001 && num1-num2 <0.0000001) { 
        return to true;
    }
    return false;
}

bool doesHasSubtree(TreeNode* pNode1,TreeNode* pNode2){
    if(pNode2 == nullptr) return true;
    if(pNode1 == nullptr) return false;
    if(equals(pNode1->val,pNode2->val)){
        return doesHasSubtree(pNode1->left,pNode2->left) && doesHasSubtree(pNode1->right,pNode2->right);
    }
    return false;
}

bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
    bool result = false;
    if(pRoot1 != nullptr && pRoot2 != nullptr){
        if(equals(pRoot1->val,pRoot2->val)){
            result = doesHasSubtree(pRoot1,pRoot2);
        }
        if(!result){
            result = HasSubtree(pRoot1->left,pRoot2);
        }
        if(!result){
            result = HasSubtree(pRoot1->right,pRoot2);
        }

    }
    return result;
}

int main()
{
    TreeNode *node7 = new TreeNode(7);
    TreeNode *node6 = new TreeNode(4);
    TreeNode *node5 = new TreeNode(3);
    TreeNode *node4 = new TreeNode(9);
    TreeNode *node3 = new TreeNode(7);
    TreeNode *node2 = new TreeNode(8);
    TreeNode *node1 = new TreeNode(8);

    node1->left = node2;
    node1->right = node3;
    node2->left = node4;
    node2->right = node5;
    node5->left = node6;
    node5->right =node7;

    TreeNode *node31 = new TreeNode(2);
    TreeNode *node21 = new TreeNode(9);
    TreeNode *node11 = new TreeNode(8);

    node11->left = node21;
    node11->right = node31;

    cout<<HasSubtree(node1,node11)<<endl;
    
    return 0;
}

   

Guess you like

Origin www.cnblogs.com/buaaZhhx/p/11918956.html