1. 程式人生 > >LeetCode951-翻轉等價二叉樹

LeetCode951-翻轉等價二叉樹

bsp 等價 int nbsp != ron span 分析 ==

問題:翻轉等價二叉樹

我們可以為二叉樹 T 定義一個翻轉操作,如下所示:選擇任意節點,然後交換它的左子樹和右子樹。

只要經過一定次數的翻轉操作後,能使 X 等於 Y,我們就稱二叉樹 X 翻轉等價於二叉樹 Y。

編寫一個判斷兩個二叉樹是否是翻轉等價的函數。這些樹由根節點 root1root2 給出。

示例:

輸入: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]
輸出:true
解釋:We flipped at nodes with values 1, 3, and 5.

技術分享圖片

提示:

  1. 每棵樹最多有 100 個節點。
  2. 每棵樹中的每個值都是唯一的、在 [0, 99] 範圍內的整數。

鏈接:https://leetcode-cn.com/contest/weekly-contest-113/problems/flip-equivalent-binary-trees/

分析:

1.兩個空指針相同

2.一個空一個非空,不相同

3.如果兩個非空,值不等,不相同

4.兩個非空且值相等,設為r1,r2,那麽r1.left=r2.left 且r1.right=r2.right,或者r1.left=r2.right 且r1.right=r2.left,則相等,否則不等,遞歸即可。

AC Code:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool flipEquiv(TreeNode* root1, TreeNode* root2) {
13 bool ret = false; 14 ret = check(root1, root2); 15 return ret; 16 } 17 bool check(TreeNode* root1, TreeNode* root2) 18 { 19 if (root1 == nullptr && root2 == nullptr) 20 { 21 return true; 22 } 23 if (root1 != nullptr && root2 != nullptr) 24 { 25 if (root1->val != root2->val) 26 { 27 return false; 28 } 29 else 30 { 31 32 return (check(root1->left, root2->left) && check(root1->right, root2->right))|| check(root1->left, root2->right) && check(root1->right, root2->left); 33 34 } 35 } 36 else 37 { 38 return false; 39 } 40 41 42 } 43 };

其他:

1.第一code:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool flipEquiv(TreeNode* root1, TreeNode* root2) {
13         if (root1 == nullptr && root2 == nullptr)
14             return true;
15 
16         if (root1 == nullptr || root2 == nullptr)
17             return false;
18 
19         if (root1->val != root2->val)
20             return false;
21 
22         if (flipEquiv(root1->left, root2->left))
23             return flipEquiv(root1->right, root2->right);
24 
25         return flipEquiv(root1->left, root2->right) && flipEquiv(root1->right, root2->left);
26     }
27 };

2.雖然AC一次過了,不過測試的時候例子錯了,所有的值使用前先判斷是否為空,之前在這個上面栽過跟頭,不過還是沒記住,近期貌似也就周末參加個周賽了,手生了。

LeetCode951-翻轉等價二叉樹