572. Subtree of Another Tree(python+cpp)

本文探讨了如何判断一棵树是否是另一棵树的子树或子结构,提供了Python和C++代码实现,详细解析了isSub()和isSame()函数的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.
Example 1:
Given tree s:

     3
    / \    
   4   5   
  / \  
 1   2 

Given tree t:

  4    
 / \  
1   2

Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:

     3
    / \    
   4   5   
  / \  
 1   2
    /    
   0 

Given tree t:

  4   
 / \  
1   2

Return false.

解释:
判断一棵树是不是另一颗树的子树,注意子树的要求是小树的叶子节点在大树中也是叶子节点,和剑指offer中判断一棵树是不是另一棵树的子结构不一样。比如上面的实例2,树t是树s的子结构但是不是它的子树。
判断一棵树是不是另一棵树的子结构(ps:空树不是任意一个树的子结构),python代码:

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def HasSubtree(self, pRoot1, pRoot2):
        # write code here
        #判断树A以r为根节点的子树是不是和树B有相同的结构
        def isSub(t1,t2):
            if not t2:
                return True
            elif not t1:
                return False
            else:
                return t1.val==t2.val and isSub(t1.left,t2.left) and isSub(t1.right,t2.right)
        if not pRoot1 or not pRoot2:
            return False
        #在A中查找与根结点一样的结点
        return isSub(pRoot1,pRoot2) or self.HasSubtree(pRoot1.left,pRoot2) or self.HasSubtree(pRoot1.right,pRoot2)

需要用到100. Same Tree(python+cpp),注意上面的isSub()isSame()有一些区别,isSub()要求只要有部分结构相同就可以但是isSame()要求整个结构的都要相同。
python代码:

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

class Solution(object):
    def isSubtree(self, s, t):
        """
        :type s: TreeNode
        :type t: TreeNode
        :rtype: bool
        """
        def isSame(r1,r2):
            if r1 and r2:
                return r1.val==r2.val and isSame(r1.left,r2.left) and isSame(r1.right,r2.right)
            return r1==r2
        if not t:
            return True
        elif not s:
            return False
        return isSame(s,t) or self.isSubtree(s.left,t) or self.isSubtree(s.right,t)

c++代码:

/**
 * 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 isSubtree(TreeNode* s, TreeNode* t) {
        if (!t)
            return true;
        else if(!s)
            return false;
        return isSame(s,t) or isSubtree(s->left,t) or isSubtree(s->right,t);
    }
    bool isSame(TreeNode*r1,TreeNode*r2)
    {
        if (r1 &&r2)
            return r1->val==r2->val && isSame(r1->left,r2->left) &&isSame(r1->right,r2->right);
        return r1==r2;
    }
};

总结:
还有先把树结构转换成str再比较的,我还是觉得这种解法更经典一点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值