【leetcode】951. Flip Equivalent Binary Trees(示例代码)

栏目: nginx · 发布时间: 2021-01-25

来源:cnblogs.com

简介  这篇文章主要介绍了【leetcode】951. Flip Equivalent Binary Trees(示例代码)以及相关的经验技巧,文章约5297字,浏览量113,点赞数6,值得参考!

题目如下:

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

解题思路:从两个根节点开始分别同步遍历两棵树,如果左右子树相同则表示不用交换;如果左右互相等于对方则交换;否则表示无法交换。

代码如下:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    res = True
    def verify(self,node1,node2):
        leftV1 = None if node1.left == None else node1.left.val
        leftV2 = None if node2.left == None else node2.left.val
        rightV1 = None if node1.right == None else node1.right.val
        rightV2 = None if node2.right == None else node2.right.val
        if leftV1 == leftV2 and rightV1 == rightV2:
            return 0
        elif leftV1 == rightV2 and rightV1 == leftV2:
            return 1
        else:
            return -1
    def traverse(self,node1,node2):
        if node1 == None or node2 == None:
            return
        ret = self.verify(node1,node2)
        if ret == 0:
            self.traverse(node1.left,node2.left)
            self.traverse(node1.right, node2.right)
        elif ret == 1:
            node2.left,node2.right = node2.right,node2.left
            self.traverse(node1.left, node2.left)
            self.traverse(node1.right, node2.right)
        else:
            self.res = False

    def flipEquiv(self, root1, root2):
        """
        :type root1: TreeNode
        :type root2: TreeNode
        :rtype: bool
        """
        if (root1 == None) ^ (root2 == None):
            return False
        self.res = True
        self.traverse(root1,root2)
        return self.res

 


以上就是本文的全部内容,希望对大家的学习有所帮助,版权归原作者或者来源机构所有,感谢作者,如果未能解决你的问题,请参考以下文章。

[LeetCode] Flip Game 翻转游戏

LeetCode Flip Game II(示例代码)

[LeetCode] Flip Game 翻转游戏之二

LeetCode–Flip Game(示例代码)

[LeetCode] Random Flip Matrix 随机翻转矩阵