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
Robert Gouveia
2 hours agoMatt Gaetz REJECTS Report, Sues Committee; Luigi Fan Club Arrives; Biden Commutes; Festivus Waste
2,706 watching -
58:10
Kimberly Guilfoyle
4 hours agoAmerica is Back & The Future is Bright: A Year in Review | Ep. 183
15.2K15 -
3:03:27
vivafrei
9 hours agoEp. 242: Barnes is BACK AGAIN! Trump, Fani, J6, RFK, Chip Roy, USS Liberty AND MORE! Viva & Barnes
52.8K21 -
LIVE
Dr Disrespect
7 hours ago🔴LIVE - DR DISRESPECT - MARVEL RIVALS - GOLD VANGUARD
3,475 watching -
1:15:00
Awaken With JP
6 hours agoMerry Christmas NOT Happy Holidays! Special - LIES Ep 71
75.8K84 -
1:42:21
The Quartering
7 hours agoTrump To INVADE Mexico, Take Back Panama Canal Too! NYC Human Torch & Matt Gaetz Report Drops!
78.9K45 -
2:23:15
Nerdrotic
7 hours ago $8.26 earnedA Very Merry Christmas | FNT Square Up - Nerdrotic Nooner 453
42.9K4 -
1:14:05
Tucker Carlson
7 hours ago“I’ll Win With or Without You,” Teamsters Union President Reveals Kamala Harris’s Famous Last Words
122K270 -
1:58:31
The Dilley Show
7 hours ago $27.24 earnedTrump Conquering Western Hemisphere? w/Author Brenden Dilley 12/23/2024
109K27 -
1:09:59
Geeks + Gamers
8 hours agoSonic 3 DESTROYS Mufasa And Disney, Naughty Dog Actress SLAMS Gamers Over Intergalactic
70.5K19