Leetcode刷题记录——951. 翻转等价二叉树

Leetcode刷题记录——951. 翻转等价二叉树_第1张图片

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:
        if root1 == None and root2 == None:
            return True
        elif root1 == None or root2 == None or root1.val != root2.val:
            return False
        return (self.flipEquiv(root1.left,root2.left) and self.flipEquiv(root1.right,root2.right)) or (self.flipEquiv(root1.left,root2.right) and self.flipEquiv(root1.right,root2.left))
        #逻辑是:对于非空且值相等的两个根节点,只需在如下两种情况满足一种即为True
        #情况1:不需翻转 则结果为f(r1.left,r2.left) and f(r1.right,r2.right)
        #情况2:需要翻转 则结果为f(r1.left,r2.right) and f(r1.right,r2.left)
        

你可能感兴趣的:(leetcode,python编程技巧)