Flip Equivalent Binary Trees in C++

C++Server Side ProgrammingProgramming

Suppose we have a binary tree. We have to flip the binary tree. The flip indicates: choose any node, and swap the left and right child subtrees. Now a binary tree X is flip equivalent to a binary tree Y if and only if we can make Y from X, after some number of flip operations. We have to write a method that determines whether two binary trees are flip equivalent. The trees are given by root nodes root1 and root2. So if the trees are −

Then the output will be true, if we flip nodes with values 1, 3 and 5.

To solve this, we will follow these steps −

  • Define one recursive function solve(), this will take two trees t1 and t2.

  • if root1 and root2 are null, then return true

  • otherwise when root1 is null or root2 is null, then return false

  • otherwise when (t1 and t2 both have no left subtrees) or (t1 and t2 both have left subtrees, and values of the left subtrees of these two nodes are same), then

    • return solve(left of root1, left of root2) and solve(right of root1, right of root2)

  • otherwise

    • return solve(left of root1, right of root2) and solve(right of root1, left of root2)

Let us see the following implementation to get better understanding −


 Live Demo

#include <bits/stdc++.h>
using namespace std;
class TreeNode{
   int val;
   TreeNode *left, *right;
   TreeNode(int data){
      val = data;
      left = NULL;
      right = NULL;
void insert(TreeNode **root, int val){
   queue<TreeNode*> q;
      TreeNode *temp = q.front();
         if(val != NULL)
            temp->left = new TreeNode(val);
            temp->left = new TreeNode(0);
         if(val != NULL)
            temp->right = new TreeNode(val);
            temp->right = new TreeNode(0);
TreeNode *make_tree(vector<int> v){
   TreeNode *root = new TreeNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      insert(&root, v[i]);
   return root;
class Solution {
   bool flipEquiv(TreeNode* root1, TreeNode* root2) {
      if(!root1 && !root2)return true;
      else if(!root1 || !root2)return false;
      else if(root1->val != root2->val) return false;
      else if((!root1->left && !root2->left) || (root1->left && root2->left && root1->left->val ==          root2-      >left->val)){
         return flipEquiv(root1->left, root2->left) && flipEquiv(root1->right, root2->right);
         return flipEquiv(root1->left, root2->right) && flipEquiv(root1->right, root2->left);
   vector<int> v = {1,2,3,4,5,6,NULL,NULL,NULL,7,8};
   TreeNode *r1 = make_tree(v);
   vector<int> v1 = {1,3,2,NULL,6,4,5,NULL,NULL,NULL,NULL,NULL,NULL,8,7};
   TreeNode *r2 = make_tree(v);
   Solution ob;
   cout << (ob.flipEquiv(r1, r2));




Published on 05-Mar-2020 10:23:24