Flip Equivalent Binary Trees

medium binary tree dfs recursion

Problem

A flip operation on a binary tree swaps the left and right children of any node. Two binary trees are flip equivalent if and only if one can be turned into the other after some number of flip operations. Given the roots of two binary trees root1 and root2, return true if the trees are flip equivalent.

Inputroot1 = [1,2,3,4,5,6,null,null,null,7,8], root2 = [1,3,2,null,6,4,5,null,null,null,null,8,7]
Outputtrue
Flipping the children at node 1 and at node 5 turns the first tree into the second.

def flip_equiv(a, b):
    if a is None and b is None:
        return True
    if a is None or b is None or a.val != b.val:
        return False
    return (flip_equiv(a.left, b.left) and flip_equiv(a.right, b.right)) or \
           (flip_equiv(a.left, b.right) and flip_equiv(a.right, b.left))
function flipEquiv(a, b) {
  if (a === null && b === null) return true;
  if (a === null || b === null || a.val !== b.val) return false;
  return (flipEquiv(a.left, b.left) && flipEquiv(a.right, b.right)) ||
         (flipEquiv(a.left, b.right) && flipEquiv(a.right, b.left));
}
class Solution {
    public boolean flipEquiv(TreeNode a, TreeNode b) {
        if (a == null && b == null) return true;
        if (a == null || b == null || a.val != b.val) return false;
        return (flipEquiv(a.left, b.left) && flipEquiv(a.right, b.right))
            || (flipEquiv(a.left, b.right) && flipEquiv(a.right, b.left));
    }
}
bool flipEquiv(TreeNode* a, TreeNode* b) {
    if (a == nullptr && b == nullptr) return true;
    if (a == nullptr || b == nullptr || a->val != b->val) return false;
    return (flipEquiv(a->left, b->left) && flipEquiv(a->right, b->right))
        || (flipEquiv(a->left, b->right) && flipEquiv(a->right, b->left));
}
Time: O(n) Space: O(h)