劍指Offer(Python多種思路實現):樹的子結構

劍指Offer(Python多種思路實現):樹的子結構

面試26題:

題目:樹的子結構

題:輸入兩棵二叉樹A和B,判斷B是不是A的子結構。

解題思路一:遞歸,注意空指針的情況。

class Solution:
    def HasSubtree(self, pRoot1, pRoot2):
        # write code here
        res=False
        if pRoot1 and pRoot2:
            if pRoot1.val==pRoot2.val:
                res=self.SubtreeCore(pRoot1,pRoot2)
            if not res:
                res=self.HasSubtree(pRoot1.left,pRoot2)
            if not res:
                res=self.HasSubtree(pRoot1.right,pRoot2)
        return res
    
    def SubtreeCore(self,pRoot1,pRoot2):
        if pRoot2==None:
            return True
        if pRoot1==None:
            return False
        if pRoot1.val!=pRoot2.val:
            return False
        return self.SubtreeCore(pRoot1.left,pRoot2.left) and self.SubtreeCore(pRoot1.right,pRoot2.right)

解題思路二:

def is_subtree(s: 'TreeNode', t: 'TreeNode') -> 'bool':

    def is_same(s, t):
        if s and t:
            equal = s.val==t.val
            if not t.left and not t.right:
                return equal
            else:
                return (equal and is_same(s.left, t.left) and
                        is_same(s.right, t.right))
        else:
            return s is t
    stack = s and [s]
    while stack:
        node = stack.pop()
        if node:
            res = is_same(node, t)
            if res:
                return True
            stack.append(node.right)
            stack.append(node.left)
    return False
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章