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.
Write a function that determines whether two binary trees are flip equivalent. The trees are given by root nodes root1
and root2
.
Example 1:
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.
Note:
- Each tree will have at most
100
nodes. - Each value in each tree will be a unique integer in the range
[0, 99]
.
這道題說是可以交換二叉樹中任意一個的結點的左右子結點,其實也就是交換了左右子樹。現在給了兩棵二叉樹,問能不能通過交換子結點操作來變成相同的樹。博主拿到題目以后,掃了一眼難度,是 Medium,大概猜到了這道題目不會過於復雜。對於二叉樹的題目,根據博主多年的刷題經驗,十有八九都是用遞歸,這道題也不例外。首先來分析一些 corner case,當兩個給定的根結點都為空的時候,此時應該返回 true 的,因為兩個空樹可以看作是相等的。其次當一個為空,另一個不為空的時候,一定是返回 false 的,或者當兩個根結點的值不相等時,也是返回 false 的。當兩個根結點值相同時,接下來就是要對子結點調用遞歸了,若是對兩個左右子結點分別調用遞歸函數均返回 true,說明整個肯定是返回 true 的沒有問題,即便返回 false 了也不要緊,因為這里還可以利用交換子結點的性質再調用一遍遞歸函數,此時 root1 的左子結點對應 root2 的右子結點,root1 的右子結點對應 root2 的左子結點,這個若返回 true 的話也行,參見代碼如下:
class Solution {
public:
bool flipEquiv(TreeNode* root1, TreeNode* root2) {
if (!root1 && !root2) return true;
if (!root1 || !root2 || root1->val != root2->val) return false;
return (flipEquiv(root1->left, root2->left) && flipEquiv(root1->right, root2->right)) || (flipEquiv(root1->left, root2->right) && flipEquiv(root1->right, root2->left));
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/951
參考資料:
https://leetcode.com/problems/flip-equivalent-binary-trees/