加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

[Swift Weekly Contest 113]LeetCode951. 翻转等价二叉树 | Flip

发布时间:2020-12-14 05:09:31 所属栏目:百科 来源:网络整理
导读: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

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. 

?

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.

?

提示:

  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 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读