Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了[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

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 arflip 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. 

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

 

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.

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

 

提示

  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 }

大佬总结

以上是大佬教程为你收集整理的[Swift Weekly Contest 113]LeetCode951. 翻转等价二叉树 | Flip Equivalent Binary Trees全部内容,希望文章能够帮你解决[Swift Weekly Contest 113]LeetCode951. 翻转等价二叉树 | Flip Equivalent Binary Trees所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。