劍指offer——樹的子結構

題目描述

輸入兩棵二叉樹A,B,判斷B是否是A的子結構。(ps:咱們約定空樹不是任意一個樹的子結構)
 
# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
def IsSubtree(root1,root2):
    if root2==None:
        return True
    elif root1==None:
        return False
    elif root1.val==root2.val:
        return IsSubtree(root1.left,root2.left)and IsSubtree(root1.right,root2.right)
    else:
        return False
        
class Solution:
    def HasSubtree(self, pRoot1, pRoot2):
        # write code here
        if pRoot2 == None or pRoot1==None:
            return False
        return IsSubtree(pRoot1,pRoot2) or self.HasSubtree(pRoot1.left,pRoot2) or self.HasSubtree(pRoot1.right,pRoot2)
        
相關文章
相關標籤/搜索