From 41d8d6a8602b8dbaf8cf746e828750a5bde6aaf1 Mon Sep 17 00:00:00 2001 From: gameloader Date: Thu, 24 Oct 2024 13:53:56 +0800 Subject: [PATCH] leetcode update --- content/posts/leetcode.md | 46 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/content/posts/leetcode.md b/content/posts/leetcode.md index 0568df4..18c23e0 100644 --- a/content/posts/leetcode.md +++ b/content/posts/leetcode.md @@ -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)); + } +}; +```