Description

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

Solutions

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def is_subtree(self, pRoot1, pRoot2):
        if pRoot2 is None:
            return True
        
        if pRoot1 is None:
            return False
        
        result = True
        
        if pRoot1.val == pRoot2.val:
            result = self.is_subtree(pRoot1.left, pRoot2.left) and self.is_subtree(pRoot1.right, pRoot2.right)
        else:
            result = False
        return result
    
    def HasSubtree(self, pRoot1, pRoot2):
        result = False
        
        if pRoot1 is not None and pRoot2 is not None:
            if pRoot1.val == pRoot2.val:
                result = self.is_subtree(pRoot1, pRoot2)
            if not result:
                result = self.HasSubtree(pRoot1.left, pRoot2)  
            if not result:
                result = self.HasSubtree(pRoot1.right, pRoot2)
        
        return result

需要注意在 HasSubtree 函数中对 if 的情况讨论。还是要强调对过程的透彻分析,才能写出正确的代码。除了

References

  1. 018. 树的子结构