Flip Equivalent Binary Trees Solutions in C++
Number 951
Difficulty Medium
Acceptance 65.8%
Link LeetCode
Other languages Python
Solutions
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/flip-equivalent-binary-trees//// Author : liuyubobobo/// Time : 2018-12-01#include <iostream>using namespace std;/// Recursion/// Time Complexity: O(min(N1, N2))/// Space Complexity: O(min(h1, h2))/// Definition for a binary tree node.struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public:bool flipEquiv(TreeNode* root1, TreeNode* root2) {return check(root1, root2);}private:bool check(TreeNode* node1, TreeNode* node2){if(!node1 && !node2)return true;if(!node1 || !node2)return false;if(node1->val != node2->val)return false;return (check(node1->left, node2->left) && check(node1->right, node2->right)) ||(check(node1->right, node2->left) && check(node1->left, node2->right));}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/flip-equivalent-binary-trees//// Author : liuyubobobo/// Time : 2018-12-01#include <iostream>#include <vector>using namespace std;/// Canonical Traversal/// Time Complexity: O(N1 + N2)/// Space Complexity: O(N1 + N2)/// Definition for a binary tree node.struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public:bool flipEquiv(TreeNode* root1, TreeNode* root2) {vector<int> vec1, vec2;dfs(root1, vec1);// for(TreeNode* node: vec1)// cout << (node ? node->val : -1) << " ";// cout << endl;dfs(root2, vec2);// for(TreeNode* node: vec2)// cout << (node ? node->val : -1) << " ";// cout << endl;return vec1 == vec2;}private:void dfs(TreeNode* node, vector<int>& vec){vec.push_back(node ? node->val : -1);if(!node)return;int L = node->left ? node->left->val : -1;int R = node->right ? node->right->val : -1;if(L <= R)dfs(node->left, vec), dfs(node->right, vec);elsedfs(node->right, vec), dfs(node->left, vec);}};int main() {cout << Solution().flipEquiv(NULL, new TreeNode(1)) << endl;// Falsereturn 0;}