Tree substructure-traverse the subtree

Tree substructure

Enter two binary trees A and B to determine whether B is a substructure of A. (It is agreed that an empty tree is not a substructure of any tree)
B is a substructure of A, that is, A has the same structure and node value as B.

For example:
given tree A:

     3
    / \
   4   5
  / \
 1   2

Given tree B:

   4 
  /
 1

Returns true because a subtree of B and A has the same structure and node values.

Example 1:
Input: A = [1,2,3], B = [3,1]
Output: false

Example 2:
Input: A = [3,4,5,1,2], B = [4,1]
Output: true
limit:

0 <= number of nodes <= 10000


analysis

Traverse all the subtrees of A and compare it with the B tree.

solution

bool aha(struct TreeNode* A, struct TreeNode* B){
    
    
    // 如果A节点为空,B不为空,说明此时已经不匹配,返回false
    if(A == NULL && B){
    
    
        return false;
    }
    // 如果B为空,说明当前节点是空节点,从某处到此的一个分支已经完成了,如果没有false出现,说明这个子树是A的子树
    if(B == NULL){
    
    
        return true;
    }
    // A与B不等,且B不为空
    if(A->val != B->val && B != NULL)
        // 此时应该return false,因为当前节点不一定是原始B的根节点,所以不能继续向下判断
        return false;
    // 如果AB相同,此时可以往下遍历,确保AB的左右子树都相同
    if(A->val == B->val){
    
    
        return aha(A->left, B->left) && aha(A->right, B->right);
    }
    return false;
}

void dfs_A(struct TreeNode* A, struct TreeNode* B, bool *flag){
    
    
    // 如果A为空了,不继续往下遍历
    if(A == NULL){
    
    
        return;
    }
    // A子树与B比较
    if(aha(A, B)){
    
    
        // A, B匹配成功
        *flag = true;
        return;
    }
    else{
    
    
        // 遍历A树,
        dfs_A(A->left, B, flag);
        dfs_A(A->right, B, flag);
    }
}

bool isSubStructure(struct TreeNode* A, struct TreeNode* B){
    
    
    //代码的鲁棒性,空树,算吗?
    if(A == NULL && B == NULL){
    
    
        return false;
    }
    // B为NULL,返回false
    if(B == NULL)
        return false;
    bool *flag = malloc(sizeof(bool));
    *flag = false;
    dfs_A(A,B,flag);
    return *flag;
}

Guess you like

Origin blog.csdn.net/qq_39378657/article/details/109637886