Flip Equivalent Binary Trees
Understand and solve the interview question "Flip Equivalent Binary Trees".
We'll cover the following...
Description
Let’s start by defining what a flip operation for a binary tree is. We can define it as:
“Choosing any node and swapping the right and left child subtrees.”
A binary tree, T, is flip equivalent to another binary tree, S, if we can make T
equal to S
after some number of flip
operations.
Given the roots of two binary trees, root1
and root2
, you have to find out whether the trees are flip equivalent to each other or not. The flipEquiv
function should return true
if the binary trees are equivalent. Otherwise, it will return false
.
Example
Let’s look at the example below:
Coding exercise
#include "TreeNode.h"bool flipEquiv(TreeNode* root1, TreeNode* root2) {// write your code herereturn false;}
Solution
We implement the flipEquiv
function using recursion. Like any recursive function, we start by defining the base conditions. We have two base conditions:
-
If
root1
orroot2
is null, they are equivalent if and only if they are bothnull
. -
If
root1
androot2
have different values, they aren’t equivalent.
Lastly, we move on to the recursive part and check whether the children of root1
are equivalent to the children of root2
. We pair the children in two different ways:
- Compare the left subtree of
root1
with the