Input: root1 =[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]Output: trueExplanation: We flipped at nodes with values 1,3, and 5.
To determine if two binary trees are flip equivalent, we need to recursively check the following conditions for corresponding subtrees:
Both roots should be null, or both should have the same value. (This can be written more concisely as - If at least one of the two root nodes is null, are they equal? if yes, true; if no, false;)
otherwise, neither node is null; if the values of the two nodes are:
Recursively check if their children are equivalent. This can occur in two situations:
No flip: The left child of root1 is equivalent to the left child of root2 and the right child of root1 is equivalent to the right child of root2.
Flip: The left child of root1 is equivalent to the right child of root2 and the right child of root1 is equivalent to the left child of root2.
Basically, if both the trees match exactly recursively, we can still flip them. If they are mirror of each other, they are still equal, because that is waht we want to do.
publicclassSolution {
publicbooleanflipEquiv(TreeNode root1, TreeNode root2) {
// If both nodes are null, they are flip equivalentif (root1 ==null&& root2 ==null) {
returntrue;
}
// If one is null or their values are not equal, they are not flip equivalentif (root1 ==null|| root2 ==null|| root1.val!= root2.val) {
returnfalse;
}
// Perform the recursive checks// Check if they are flip equivalent without a flipboolean noFlip = flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right);
// Check if they are flip equivalent with a flipboolean flip = flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left);
// Return true if either scenario holdsreturn noFlip || flip;
}
}
classSolution:
defflipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:
# If both nodes are null, they are flip equivalentif root1 isNoneand root2 isNone:
returnTrue# If one is null or their values are not equal, they are not flip equivalentif root1 isNoneor root2 isNoneor root1.val != root2.val:
returnFalse# Perform the recursive checks# Check if they are flip equivalent without a flip no_flip = self.flipEquiv(root1.left, root2.left) and self.flipEquiv(root1.right, root2.right)
# Check if they are flip equivalent with a flip flip = self.flipEquiv(root1.left, root2.right) and self.flipEquiv(root1.right, root2.left)
# Return true if either scenario holdsreturn no_flip or flip