Premium Only Content

951. Flip Equivalent Binary Trees
Code:-
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool flipEquiv(TreeNode* root1, TreeNode* root2) {
return bfs(root1, root2);
}
private:
bool bfs(TreeNode* root1, TreeNode* root2) {
if (root1 == nullptr && root2 == nullptr) {
return true;
}
if (root1 == nullptr || root2 == nullptr) {
return false;
}
if (root1->val != root2->val) {
return false;
}
return (bfs(root1->left, root2->left) && bfs(root1->right, root2->right)) ||
(bfs(root1->left, root2->right) && bfs(root1->right, root2->left));
}
};
Question:-
For a binary tree T, we can define a flip operation as follows: choose any node, and swap the left and right child subtrees.
A 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.
Given the roots of two binary trees root1 and root2, return true if the two trees are flip equivalent or false otherwise.
Example 1:
Flipped Trees Diagram
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: true
Explanation: We flipped at nodes with values 1, 3, and 5.
Example 2:
Input: root1 = [], root2 = []
Output: true
Example 3:
Input: root1 = [], root2 = [1]
Output: false
Constraints:
The number of nodes in each tree is in the range [0, 100].
Each tree will have unique node values in the range [0, 99].
-
LIVE
Game On!
16 hours agoNFL Week 4 Betting Report Preview!
1,763 watching -
21:05
Adam Does Movies
21 hours ago $0.62 earnedAlien: Earth Episode 8 - Recap
3.26K3 -
18:49
World2Briggs
18 hours ago $0.31 earnedTop 10 States To retire in 2026 According to Experts
1.62K4 -
19:03
Blackstone Griddles
13 hours agoParmesan Ranch Chicken Sandwich oxn the Blackstone Griddle
3.84K3 -
LIVE
BEK TV
23 hours agoTrent Loos in the Morning - 9/26/2025
191 watching -
LIVE
The Bubba Army
22 hours agoJimmy Kimmel's Audience Plummets by 20 MILLION! - Bubba the Love Sponge® Show | 9/26/25
1,422 watching -
17:24
Sponsored By Jesus Podcast
21 hours agoLoving Our ENEMIES & Praying for Those Who Hurt Us
3.43K3 -
4:22
NAG Daily
14 hours agoSaving Grace #4 — Is The BIBLE Wrong?
10.7K5 -
6:14
Sugar Spun Run
1 day ago $1.02 earnedApple Cobbler
7.73K4 -
31:26
Clownfish TV
6 days agoJimmy Kimmel GONE FOR GOOD?! Insider Claims Disney is DONE! | Clownfish TV
13.4K27