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].
-
16:59
Chris From The 740
17 hours ago $0.18 earnedIs Bigger Better? - The Gideon Optics Mediator 2 Is Here!
1.92K -
7:58
Blackstone Griddles
14 hours agoTennessee Mountain Burgers on the Blackstone Griddle
4.72K1 -
43:32
NAG Daily
15 hours agoThe Rezendes Rundown Ep. 17 - Epstein's Birthday Book
2.66K3 -
9:28
Freedom Frontline
19 hours agoEric Schmitt Drops DAMNING Biden Video And The Media PANICS
3.42K4 -
24:49
DeVory Darkins
1 day ago $28.95 earnedTrump drops shocking news on Omar as DC Mayor gets humiliated during painful hearing
144K170 -
LIVE
Times Now World
1 day agoLIVE | Lavrov Warns West: Humiliation of Russia Will Have Consequences | Russia | Putin | World News
150 watching -
55:42
Coin Stories with Natalie Brunell
1 day agoSaylor vs Wall Street – Why Bitcoin Wins
39.3K8 -
45:26
The Why Files
3 days agoCONPLAN 8888: The Secret Plan to Survive the Zombie Apocalypse
39.1K31 -
10:56
Liberty Hangout
2 days agoThank You Charlie
196K55 -
1:49:51
Steve-O's Wild Ride! Podcast
8 days ago $9.59 earnedChet Hanks Found God On Chat GPT | Wild Ride #266
76.1K8