LeetCode 951. Flip Equivalent Binary Trees解题报告(python)

1111. Maximum Nesting Depth of Two Valid Parentheses Strings

  1. Flip Equivalent Binary Treespython solution

题目描述

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.

LeetCode 951. Flip Equivalent Binary Trees解题报告(python)_第1张图片

解析

仍然是递归解法。

class Solution:
    def flipEquiv(self, root1: TreeNode, root2: TreeNode) -> bool:
        if root1 is None and root2 is None: return True
        elif root1 is None or root2 is None: return False
        elif root1.val!=root2.val: return False
        elif self.flipEquiv(root1.left,root2.left) and self.flipEquiv(root1.right,root2.right): return True
        elif self.flipEquiv(root1.left,root2.right) and self.flipEquiv(root1.right,root2.left): return True
        else:
            return False   

Reference

https://leetcode.com/problems/flip-equivalent-binary-trees/discuss/337371/Recursive-Python-solution-with-explanation-and-analysis

你可能感兴趣的:(LeetCode)