26.樹的子結構

題目描述

輸入兩棵二叉樹A,B,判斷B是不是A的子結構。(ps:我們約定空樹不是任意一個樹的子結構)

思路:遍歷樹A中的節點,看與樹B根節點的值是否相等,相等的話,遞歸比較左右子樹。不相等的話,接着遍歷樹A。樹的遍歷也是使用遞歸的方式進行實現。需要注意的是,由於空樹不是任意一個樹的子結構,所以只有當兩樹都不爲空時才進行判斷B是否爲A的子樹。在比較相等節點的左右子樹是否相等時,如果B已經爲空了,那麼說明已經找到了。如果B不爲空但是A已經空了,那麼說明沒找到。

python題解:

# -*- 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
        result=False
        if pRoot1 and pRoot2:
            if pRoot1.val==pRoot2.val:
                result=self.JudgeSubtree(pRoot1,pRoot2)
            if not result:
                result=self.HasSubtree(pRoot1.left,pRoot2)
            if not result:
                result=self.HasSubtree(pRoot1.right,pRoot2)
        return result
                
    def JudgeSubtree(self,pRoot1,pRoot2):
        if not pRoot1 and pRoot2:
            return False
        if not pRoot2:
            return True
        if pRoot1.val!=pRoot2.val:
            return False
        return self.JudgeSubtree(pRoot1.left,pRoot2.left) and self.JudgeSubtree(pRoot1.right,pRoot2.right)
        

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章