← Home

951. Flip Equivalent Binary Trees

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
bit manipulationC++Markdown
951

This is one of those problems where the clean idea matters more than the amount of code. For 951. Flip Equivalent Binary Trees, the solution in this repository is mainly a bit manipulation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: bit manipulation.

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are flipEquiv, dfs.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01/**
02For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.
03
04A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y after some number of flip operations.
05
06Write a function that determines whether two binary trees are flip equivalent.  The trees are given by root nodes root1 and root2.
07
08 
09
10Example 1:
11
12Input: 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]
13Output: true
14Explanation: We flipped at nodes with values 1, 3, and 5.
15Flipped Trees Diagram
16 
17
18Note:
19
20Each tree will have at most 100 nodes.
21Each value in each tree will be a unique integer in the range [0, 99].
22**/
23
24//Your runtime beats 100.00 % of cpp submissions.
25/**
26 * Definition for a binary tree node.
27 * struct TreeNode {
28 *     int val;
29 *     TreeNode *left;
30 *     TreeNode *right;
31 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
32 * };
33 */
34class Solution {
35public:
36    bool flipEquiv(TreeNode* root1, TreeNode* root2) {
37        if(root1==NULL && root2==NULL){
38            return true;
39        }else if(root1==NULL ^ root2==NULL){
40            return false;
41        }else if(root1->val != root2->val){
42            return false;
43        }else{
44            return (flipEquiv(root1->left, root2->left) && flipEquiv(root1->right, root2->right)) ||
45                (flipEquiv(root1->left, root2->right) && flipEquiv(root1->right, root2->left));
46        }
47    }
48};
49
50/**
51Solution
52Approach 1: Recursion
53Intuition
54
55If root1 and root2 have the same root value, then we only need to check if their children are equal (up to ordering.)
56
57Algorithm
58
59There are 3 cases:
60
61If root1 or root2 is null, then they are equivalent if and only if they are both null.
62
63Else, if root1 and root2 have different values, they aren't equivalent.
64
65Else, let's check whether the children of root1 are equivalent to the children of root2. 
66There are two different ways to pair these children.
67**/
68
69//Java
70/**
71class Solution {
72    public boolean flipEquiv(TreeNode root1, TreeNode root2) {
73        if (root1 == root2)
74            return true;
75        if (root1 == null || root2 == null || root1.val != root2.val)
76            return false;
77
78        return (flipEquiv(root1.left, root2.left) && flipEquiv(root1.right, root2.right) ||
79                flipEquiv(root1.left, root2.right) && flipEquiv(root1.right, root2.left));
80    }
81}
82**/
83
84/**
85Complexity Analysis
86
87Time Complexity: O(min(N_1, N_2)), where N_1, N_2 are the lengths of root1 and root2.
88
89Space Complexity: O(min(H_1, H_2)), where H_1, H_2 are the heights of the trees of root1 and root2. 
90**/
91
92/**
93Approach 2: Canonical Traversal
94Intuition
95
96Flip each node so that the left child is smaller than the right, and call this the canonical representation. All equivalent trees have exactly one canonical representation.
97
98Algorithm
99
100We can use a depth-first search to compare the canonical representation of each tree. If the traversals are the same, the representations are equal.
101
102When traversing, we should be careful to encode both when we enter or leave a node.
103**/
104
105//Your runtime beats 100.00 % of cpp submissions.
106/**
107 * Definition for a binary tree node.
108 * struct TreeNode {
109 *     int val;
110 *     TreeNode *left;
111 *     TreeNode *right;
112 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
113 * };
114 */
115class Solution {
116public:
117    bool flipEquiv(TreeNode* root1, TreeNode* root2) {
118        vector<int> l1, l2;
119        
120        dfs(root1, l1);
121        dfs(root2, l2);
122        
123        // std::copy(l1.begin(), l1.end(), std::ostream_iterator<int>(std::cout, " "));
124        // cout << endl;
125        // std::copy(l2.begin(), l2.end(), std::ostream_iterator<int>(std::cout, " "));
126        
127        return l1==l2;
128    }
129    
130    void dfs(TreeNode* node, vector<int>& v){
131        if(node==NULL) return;
132        v.push_back(node->val);
133        
134        int L = node->left==NULL?-1:node->left->val;
135        int R = node->right==NULL?-1:node->right->val;
136        
137        if(L<R){
138            dfs(node->left, v);
139            dfs(node->right, v);
140        }else{
141            dfs(node->right, v);
142            dfs(node->left, v);
143        }
144        //official answer push NULL here, don't know why
145        //the algorithm can work without this line
146        //v.push_back(NULL);
147    }
148};
149
150/**
151Complexity Analysis
152
153Time Complexity: O(N_1 + N_2), where N_1, N_2 are the lengths of root1 and root2. (In Python, this is min(N_1, N_2).)
154
155Space Complexity: O(N_1 + N_2). (In Python, this is min(H_1, H_2), where H_1, H_2 are the heights of the trees of root1 and root2.) 
156**/

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.