100/101/572. Substructure equal tree / tree of images / tree

  • 100 is equal to the tree
    . Ideas: 1 first thought is conventional, pq not to None; 2 Rethinking exit conditions, pq at least one of None..
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        # 左右都没有val的情况
        if not p and not q:
            return True
        # 左右有一个没有val的情况
        if not p or not q:
            return False
        # 左右都有val的情况
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.rihgt)
  • 101 Mirror tree
  1. Mirroring conditions are equal to the value of the child's left and right children's values, and left the child's left child and right child of the right child image, and the left and right child and the child's right child of the left child image.
  2. Exit condition is left child or the right child has at least one of None
  3. Construct an auxiliary function, parameter passing to the left subtree and right subtree.
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        return self.isSymmetricHelper(root.left, root.right)

    def isSymmetricHelper(self, left, right):
        # 左右两棵树都为None的情况
        if not left and not right:
            return True
        # 左右两棵树有一个为None的情况
        if not left or not right:
            return False
        # 左右两棵树都不为None的情况
        return left.val == right.val and self.isSymmetricHelper(left.left, right.right) and self.isSymmetricHelper(left.right, right.left)
  • Substructure tree 572
    to write a helper function compare, compare claim exactly two trees, can not have the extra nodes. E.g. [2,3] and [1,2] inconsistent. compare itself is a recursive function.
    Function to determine the substructure is a recursive function, general condition determination consistent s and t, or t and consistent s children.
    def isSubtree(self, s, t):
        """
        :type s: TreeNode
        :type t: TreeNode
        :rtype: bool
        """
        if not s and not t:
            return True
        if not s or not t:
            return False
        return self.compare(s,t) or self.isSubtree(s.left,t) or self.isSubtree(s.right,t)

    def compare(self, s, t):
        if not s and not t:
            return True
        if not s or not t:
            return False
        return s.val == t.val and self.compare(s.left, t.left) and self.compare(s.right, t.right)

Guess you like

Origin blog.csdn.net/weixin_33883178/article/details/90926430