---
tags: leetcode
---
# [951. Flip Equivalent Binary Trees](https://leetcode.com/problems/flip-equivalent-binary-trees/)
---
# My Solution
## The Key Idea for Solving This Coding Question
DFS (recursion) preorder traversal.
If both subtrees are not empty, visit the subtree whose root value is smaller.
## C++ Code
```cpp=
/**
* 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) {
vector<int> traversal1, traversal2;
dfs(root1, traversal1);
dfs(root2, traversal2);
return traversal1 == traversal2;
}
private:
void dfs(TreeNode *root, vector<int> &traversal) {
if (root == nullptr) {
traversal.push_back(-1);
return;
}
traversal.push_back(root->val);
if (root->left == nullptr) {
dfs(root->right, traversal);
traversal.push_back(-1);
return;
}
if (root->right == nullptr) {
dfs(root->left, traversal);
traversal.push_back(-1);
return;
}
if (root->left->val < root->right->val) {
dfs(root->left, traversal);
dfs(root->right, traversal);
return;
}
dfs(root->right, traversal);
dfs(root->left, traversal);
}
};
```
## Time Complexity
$O(n)$
$n$ is the number of nodes in the binary tree.
## Space Complexity
$O(H)$
$H$ is the height of the binary tree.
# Miscellaneous
<!--
# Test Cases
```
[1,2,3,4,5,6,null,null,null,7,8]
[1,3,2,null,6,4,5,null,null,null,null,8,7]
```
```
[]
[]
```
```
[]
[1]
```
```
[1,2,3]
[1,2,null,3]
```
```
[0,null,1]
[]
```
```
[0,null,1]
[0,1]
```
```
[1,2,3,4,5,6,null,null,null,7,8]
[99,3,2,null,6,4,5,null,null,null,null,8,7]
```
-->