[Swift Weekly Contest 113]LeetCode951. 翻轉等價二叉樹 | Flip Equivalent Binary Trees
阿新 • • 發佈:2018-12-02
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
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
- Each value in each tree will be a unique integer in the range
[0, 99]
.
我們可以為二叉樹 T 定義一個翻轉操作,如下所示:選擇任意節點,然後交換它的左子樹和右子樹。
只要經過一定次數的翻轉操作後,能使 X 等於 Y,我們就稱二叉樹 X 翻轉等價於二叉樹 Y。
編寫一個判斷兩個二叉樹是否是翻轉等價的函式。這些樹由根節點 root1
和 root2
給出。
示例:
輸入: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.
提示:
- 每棵樹最多有
100
個節點。 - 每棵樹中的每個值都是唯一的、在
[0, 99]
範圍內的整數。
16ms
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public var val: Int 5 * public var left: TreeNode? 6 * public var right: TreeNode? 7 * public init(_ val: Int) { 8 * self.val = val 9 * self.left = nil 10 * self.right = nil 11 * } 12 * } 13 */ 14 class Solution { 15 func flipEquiv(_ root1: TreeNode?, _ root2: TreeNode?) -> Bool { 16 if root1 == nil {return root2 == nil} 17 if root2 == nil {return root1 == nil} 18 if root1!.val != root2!.val {return false} 19 if flipEquiv(root1!.left, root2!.left) && flipEquiv(root1!.right, root2!.right) 20 { 21 return true 22 } 23 if flipEquiv(root1!.left, root2!.right) && flipEquiv(root1!.right, root2!.left) 24 { 25 return true 26 } 27 return false 28 } 29 }