二叉树的子结构

剑指offer 牛客网 二叉树的子结构

# -*- coding: utf-8 -*-
"""
Created on Mon Apr  8 16:13:20 2019

@author: Administrator
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

思路:分两步
step1:两个头结点对比
step2:分别匹配左右子节点,采用递归的方式
"""

# -*- 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
        if pRoot1 == None or pRoot2 == None:    
            return False
        return self.issubtree(pRoot1,pRoot2)
    def issubtree(self,p1,p2):
        if p2 == None:  #如果p2为空了说明p2全部匹配上了,所以返回是子结构
            return True
        if p1 == None:  
            return p1 == p2     #???
        res = False
        if p1.val == p2.val:    #第一步,即比较两个头结点是否相等
            #头结点相等的情况下,递归匹配其左右子节点
            res = self.issubtree(p1.left,p2.left) and self.issubtree(p1.right,p2.right)
        #分别从左右子节点开始调用,去匹配
        return res or self.issubtree(p1.left,p2) or self.issubtree(p1.right,p2)
        
if __name__ == '__main__':
    solution = Solution()
    node_left = TreeNode(9)
    node_right = TreeNode(2)
    p_left = TreeNode(8)
    p_left.left = node_left
    p_left.right = node_right
    
    node_left = TreeNode(6)
    node_right = TreeNode(5)
    p_right = TreeNode(7)
    p_right.left = node_left
    p_right.right = node_right
    
    p1 = TreeNode(8)
    p1.left = p_left
    p1.right = p_right
    
    
    node_left = TreeNode(9)
    node_right = TreeNode(2)
    p2 = TreeNode(8)
    p2.left = node_left
    p2.right = node_right
    
    res = solution.HasSubtree(p1,p2)
    print(res)

 

posted @ 2019-04-08 17:24  weilongyitian  阅读(196)  评论(0编辑  收藏  举报