leetcode update

This commit is contained in:
gameloader 2024-10-24 13:53:56 +08:00
parent 75ce86639e
commit 41d8d6a860

View File

@ -16340,3 +16340,49 @@ public:
} }
}; };
``` ```
## day230 2024-10-24
### 951. Flip Equivalent Binary Trees
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.
![1024M2CLc5WxLfOZ](https://testingcf.jsdelivr.net/gh/game-loader/picbase@master/uPic/1024M2CLc5WxLfOZ.png)
### 题解
本题在使用dfs遍历树的基础上对dfs进行一些扩充考虑如果两棵树是翻转等价的则对于任何一个父节点其两个子节点的值是一样的只是值对应的左右子节点可能位置不同一棵树是值1在左子节点另一棵则是值1在右子节点而在使用dfs遍历时无需考虑除当前节点左右子节点之外的节点其余节点在递归时总会遍历到。
在dfs时将两棵树当前节点的指针作为参数只需判断当前两节点是否相等包括都为空或者一个为空一个不为空的情况相等继续调用dfs判断左右子树是否相同或者为镜像翻转即可。即判断左树和左树相同右树和右树相同左右子树相同或者左树和右树相同右树和左树相同左右子树翻转即可。不相等直接返回false。
### 代码
```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) {
if (root1 == nullptr && root2 == nullptr){
return true;
}
if((root1 != nullptr && root2 == nullptr)||(root1==nullptr && root2 != nullptr)||(root1->val != root2->val)){
return false;
}
return (flipEquiv(root1->left, root2->left) && flipEquiv(root1->right,root2->right)) || (flipEquiv(root1->right, root2->left) && flipEquiv(root1->left,root2->right));
}
};
```