算法设计与分析—树的子结构

题目描述:

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

示例 :
给定的树 A:
———3
—— / — \ —
— 4 —— 5
—/— \—
1 —— 2
——————
给定的树 B:
— 4
—/
1
返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。

来源:力扣(LeetCode)


算法实现:

解题思路
1、先使用层次遍历,依次遍历A的每个节点,后使用先序遍历。
2、层次遍历每次遍历一个结点都要使用先序遍历进行判断A结点的子树与B树的结构是否相等。

# 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 isSubStructure(self, A, B):
        """
        :type A: TreeNode
        :type B: TreeNode
        :rtype: bool
        """          
        queue=[]
        if A!=None and B!=None:
            queue.append(A)
        while len(queue)!=0:
            p=queue.pop()
            if self.judgeTree(p,B):
                return True
            if p.left!=None:
                queue.append(p.left)
            if p.right!=None:
                queue.append(p.right)
        return False
                
    def judgeTree(self,a,b):
        if b==None:
            return True
        if a!=None and b!=None:
            if a.val==b.val:
                return self.judgeTree(a.left,b.left) and self.judgeTree(a.right,b.right)
            else:
                return False
        return False

猜你喜欢

转载自blog.csdn.net/qq_39740279/article/details/120683236