[Swift Weekly Contest 113]LeetCode951. 翻转等价二叉树 | Flip
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? Example 1: Input: root1 = [1,2,3,4,5,6,null,7,8],root2 = [1,8,7] Output: true Explanation: We flipped at nodes with values 1,and 5.
? Note:
我们可以为二叉树 T 定义一个翻转操作,如下所示:选择任意节点,然后交换它的左子树和右子树。 只要经过一定次数的翻转操作后,能使 X 等于 Y,我们就称二叉树 X?翻转等价于二叉树 Y。 编写一个判断两个二叉树是否是翻转等价的函数。这些树由根节点? 示例: 输入:root1 = [1,root2 = [1,7] 输出:true 解释:We flipped at nodes with values 1,and 5. ? 提示:
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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |