判断树B是不是树A的子结构

题意

输入两棵二叉树A和B,判断B是不是A的子结构。

Solution

# 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 HasSubtree(self, pA, pB):
        result = False
        if pA and pB:
            if pA.val == pB.val:
                result = self.DoesTreeAHaveTreeB(pA, pB)
            if not result:
                result = self.HasSubTree(pA.left, pB)
            if not result:
                result = self.HasSubTree(pA.right, pB)
        return result

    def DoesTreeAHaveTreeB(self, pA, pB):
        if not pB:
            return True
        if not pA:
            return False
        if pA.val != pB.val:
            return False
        return self.DoesTreeAHaveTreeB(pA.left, pB.left) and self.DoesTreeAHaveTreeB(pA.right, pB.right)
posted @ 2016-11-30 10:26  BinWone  阅读(360)  评论(0编辑  收藏  举报