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:
Each tree will have at most100
nodes. 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.
提示:
每棵树最多有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 = nil10 * self.right = nil11 * }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 true22 }23 if flipEquiv(root1!.left,root2!.right) && flipEquiv(root1!.right,root2!.left)24 {25 return true26 }27 return false28 }29 }总结
以上是内存溢出为你收集整理的[Swift Weekly Contest 113]LeetCode951. 翻转等价二叉树 | Flip Equivalent Binary Trees全部内容,希望文章能够帮你解决[Swift Weekly Contest 113]LeetCode951. 翻转等价二叉树 | Flip Equivalent Binary Trees所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)