判断二叉树是不是另外一个二叉树的子树

输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构) B是A的子结构, 即 A中有出现和B相同的结构和节点值。

class Solution {
public:
    bool checkChildTree(TreeNode* A, TreeNode* B) {
        if ((A == NULL) != (B == NULL)) {
            return  false;
        }
        if (A == NULL) {
            return true;
        }
        if (A->val == B->val) {
            if (checkChildTree(A->left, B->left) && 
               checkChildTree(A->right, B->right)) {
                return true;
            } else if (checkChildTree(A->left, B->left) &&
              B->right == NULL){    // 如果左子树相当并且B树右为空
                return true;
            } else if (checkChildTree(A->right, B->right) && B->left == NULL) { // 如果右子树相等并且B树左为空
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    bool isSubStructure(TreeNode* A, TreeNode* B) {
        if (A == NULL) {
            return false;
        }
        if(checkChildTree(A, B)) {  // 查看A 节点的子树和B 树是否相等
            return true;
        } else {
            return isSubStructure(A->left, B) || isSubStructure(A->right, B);
        }
    }
};

 

posted @ 2021-03-14 19:25  HuLargeSun  阅读(143)  评论(0)    收藏  举报