ASMR LeetCode: Flip Equivalent Binary Trees | Chill Coding

Поделиться
HTML-код
  • Опубликовано: 1 дек 2024

Комментарии •

  • @LeekCodeDev
    @LeekCodeDev  Месяц назад +2

    Source Code:
    # Definition for a binary tree node.
    # class TreeNode:
    # def __init__(self, val=0, left=None, right=None):
    # self.val = val
    # self.left = left
    # self.right = right
    class Solution:
    def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
    '''
    To solve this problem, for each node, I'm going to compare the children for the
    two roots we are given. If the left and right values are the same, or they're
    just flipped, I keep recursing down the tree and return True if i reach None, because
    this means that we found no inequalities. However, if the property of the children
    values being the same gets broken, we return False up to the roots and we will
    return False! We repeat this process to get our final True or False value, whether
    we can flip the equivalent binary Tree :D
    '''
    if not root1 and not root2:
    return True
    elif not root1 or not root2:
    return False
    elif root1.val != root2.val:
    return False
    root1_left_child_val = 0 if root1.left is None else root1.left.val
    root1_right_child_val = 0 if root1.right is None else root1.right.val
    root2_left_child_val = 0 if root2.left is None else root2.left.val
    root2_right_child_val = 0 if root2.right is None else root2.right.val
    if root1_left_child_val == root2_left_child_val and root1_right_child_val == root2_right_child_val:
    return self.flipEquiv(root1.left,root2.left) and self.flipEquiv(root1.right,root2.right)
    elif root1_left_child_val == root2_right_child_val and root1_right_child_val == root2_left_child_val:
    return self.flipEquiv(root1.left,root2.right) and self.flipEquiv(root1.right,root2.left)
    else:
    return False