剑指offer | 树的子结构 | 26


思路分析

其实就是递归判断左树和右树,但是一些判断条件需要仔细思考下.

cpp

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool hasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) {
        auto p1=pRoot1,p2=pRoot2;
        if(p1==NULL || p2==NULL)return false;
        if(isPart(p1,p2))return true;
        return hasSubtree(p1->left,p2) || hasSubtree(p1->right,p2);
    }
    
    bool isPart(TreeNode* p1,TreeNode* p2){
        if(p2==NULL)return true; // 判断p2这个要放在前面
        if(p1==NULL)return false;
        if(p1->val != p2->val)return false;
        return isPart(p1->left,p2->left) && isPart(p1->right,p2->right);
    }
};

python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
        def isPart(p1,p2):
            if not p2:return True
            if not p1:return False
            if p1.val != p2.val:return False
            return isPart(p1.left,p2.left) and isPart(p1.right,p2.right)

        p1,p2=A,B
        if not p1 or not p2:
            return False
        if isPart(p1,p2):return True
        return self.isSubStructure(p1.left,p2) or self.isSubStructure(p1.right,p2)
原文地址:https://www.cnblogs.com/Rowry/p/14320345.html