微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[Swift Weekly Contest 113]LeetCode951. 翻转等价二叉树 | 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.

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,7,8],root2 = [1,8,7] Output: true Explanation: We flipped at nodes with values 1,and 5. 

Flipped Trees Diagram

@H_404_30@

 

Note:

  1. Each tree will have at most 100 nodes.
  2. Each value in each tree will be a unique integer in the range [0,99].

我们可以为二叉树 T 定义一个翻转操作,如下所示:选择任意节点,然后交换它的左子树和右子树。

只要经过一定次数的翻转操作后,能使 X 等于 Y,我们就称二叉树 X 翻转等价于二叉树 Y。

编写一个判断两个二叉树是否是翻转等价函数。这些树由根节点 root1和 root2 给出。

示例:

输入:root1 = [1,root2 = [1,7]
输出:true
解释:We flipped at nodes with values 1,and 5.
@H_404_30@ 

Flipped Trees Diagram

 

提示

  1. 每棵树最多有 100 个节点。
  2. 每棵树中的每个值都是唯一的、在 [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 }@H_404_30@ 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐