|
| 1 | +# 951. Flip Equivalent Binary Trees |
| 2 | +# 🟠 Medium |
| 3 | +# |
| 4 | +# https://leetcode.com/problems/flip-equivalent-binary-trees/ |
| 5 | +# |
| 6 | +# Tags: Tree - Depth-First Search - Binary Tree |
| 7 | + |
| 8 | +import timeit |
| 9 | +from typing import Optional |
| 10 | + |
| 11 | +from utils.binary_tree import BinaryTree, TreeNode |
| 12 | + |
| 13 | + |
| 14 | +# Use recursion, check that the values at the current node match, if |
| 15 | +# they do not, we can return false. If they do match, we need to explore |
| 16 | +# the right and left subtrees recursively both flipping them and keeping |
| 17 | +# them in their original form. |
| 18 | +# |
| 19 | +# Time complexity: O(n) - At every node, we will check two branches, |
| 20 | +# flipping the children and not flipping the children, but one of them |
| 21 | +# will fail immediately O(1) because values are unique, otherwise, it |
| 22 | +# would be O(2^n) |
| 23 | +# Space complexity: O(h) - Where h is the height of the tree, that is |
| 24 | +# the space used by the call stack. |
| 25 | +# |
| 26 | +# Runtime 0 ms Beats 100% |
| 27 | +# Memory 16.58 MB Beats 57% |
| 28 | +class Solution: |
| 29 | + def flipEquiv( |
| 30 | + self, root1: Optional[TreeNode], root2: Optional[TreeNode] |
| 31 | + ) -> bool: |
| 32 | + if not root1 or not root2: |
| 33 | + return not root1 and not root2 |
| 34 | + return root1.val == root2.val and ( |
| 35 | + ( |
| 36 | + self.flipEquiv(root1.left, root2.right) |
| 37 | + and self.flipEquiv(root1.right, root2.left) |
| 38 | + ) |
| 39 | + or ( |
| 40 | + self.flipEquiv(root1.left, root2.left) |
| 41 | + and self.flipEquiv(root1.right, root2.right) |
| 42 | + ) |
| 43 | + ) |
| 44 | + |
| 45 | + |
| 46 | +def test(): |
| 47 | + executors = [Solution] |
| 48 | + tests = [ |
| 49 | + [[], [], True], |
| 50 | + [[], [1], False], |
| 51 | + [ |
| 52 | + [1, 2, 3, 4, 5, 6, None, None, None, 7, 8], |
| 53 | + [1, 3, 2, None, 6, 4, 5, None, None, None, None, 8, 7], |
| 54 | + True, |
| 55 | + ], |
| 56 | + ] |
| 57 | + for executor in executors: |
| 58 | + start = timeit.default_timer() |
| 59 | + for _ in range(1): |
| 60 | + for col, t in enumerate(tests): |
| 61 | + sol = executor() |
| 62 | + result = sol.flipEquiv( |
| 63 | + BinaryTree.fromList(t[0]).getRoot(), |
| 64 | + BinaryTree.fromList(t[1]).getRoot(), |
| 65 | + ) |
| 66 | + exp = t[2] |
| 67 | + assert result == exp, ( |
| 68 | + f"\033[93m» {result} <> {exp}\033[91m for" |
| 69 | + + f" test {col} using \033[1m{executor.__name__}" |
| 70 | + ) |
| 71 | + stop = timeit.default_timer() |
| 72 | + used = str(round(stop - start, 5)) |
| 73 | + cols = "{0:20}{1:10}{2:10}" |
| 74 | + res = cols.format(executor.__name__, used, "seconds") |
| 75 | + print(f"\033[92m» {res}\033[0m") |
| 76 | + |
| 77 | + |
| 78 | +test() |
0 commit comments