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].
-
5:59:12
ColdHe4rted
7 hours agoOverwatch = new tank! Lets go!
13.4K -
5:19:50
SLS - Street League Skateboarding
8 days ago2024 SLS Tokyo: Women’s and Men’s Knockout Rounds
536K24 -
2:51:00
Fresh and Fit
10 hours agoWomen Claim To Give Better Dating Advice So We Did THIS...
153K87 -
5:16:50
CHiLi XDD
12 hours ago[F EM UP Friday] Take # 2 [Destiny 2] Lets Kick Some A$$! #RumbleTakeOver
75K4 -
5:13:43
ItsMossy
17 hours agoHALO WITH THE RUMBLERS (: #RUMBLETAKEOVER
60.8K1 -
1:54:08
INFILTRATION85
11 hours agoHi, I'm INFILTRATION
44.5K9 -
7:51:03
GuardianRUBY
13 hours agoRumble Takeover! The Rumblings are strong
107K5 -
4:28:45
Etheraeon
20 hours agoWorld of Warcraft: Classic | Fresh Level 1 Druid | 500 Follower Goal
72.3K3 -
3:17:21
VapinGamers
12 hours ago $4.07 earned🎮🔥Scrollin’ and Trollin’: ESO Adventures Unleashed!
50.1K2 -
10:48:40
a12cat34dog
13 hours agoGETTING AFTERLIFE UNLOCKED :: Call of Duty: Black Ops 6 :: ZOMBIES CAMO GRIND w/Bubba {18+}
42K2