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].
-
35:08
Colion Noir
7 hours agoA Bear, an AR-15, and a Home Invasion
3.8K2 -
3:05:55
TimcastIRL
4 hours agoJimmy Kimmel Refuses To Apologize Over Charlie Kirk Comments, Blames Gun Violence | Timcast IRL
125K95 -
LIVE
Laura Loomer
6 hours agoEP144: Trump Cracks Down On Radical Left Terror Cells
1,101 watching -
LIVE
Drew Hernandez
8 hours agoLEFTISTS UNITE TO DEFEND KIMMEL & ANTIFA TO BE DESIGNATED TERRORISTS BY TRUMP
949 watching -
1:12:32
The Charlie Kirk Show
4 hours agoTPUSA AT CSU CANDLELIGHT VIGIL
55.3K44 -
LIVE
Akademiks
6 hours agoCardi B is Pregnant! WERE IS WHAM????? Charlie Kirk fallout. Bro did D4VID MURK A 16 YR OLD GIRL?
1,212 watching -
2:26:15
Barry Cunningham
5 hours agoPRESIDENT TRUMP HAS 2 INTERVIEWS | AND MORE PROOF THE GAME HAS CHANGED!
76.4K59 -
1:20:27
Glenn Greenwald
6 hours agoLee Fang Answers Your Questions on Charlie Kirk Assassination Fallout; Hate Speech Crackdowns, and More; Plus: "Why Superhuman AI Would Kill Us All" With Author Nate Soares | SYSTEM UPDATE #518
92.2K32 -
1:03:06
BonginoReport
7 hours agoLyin’ Jimmy Kimmel Faces The Music - Nightly Scroll w/ Hayley Caronia (Ep.137)
151K60 -
55:40
Donald Trump Jr.
10 hours agoThe Warrior Ethos & America's Mission, Interview with Harpoon Ventures Founder Larsen Jensen | Triggered Ep275
92.4K55