1111. Maximum Nesting Depth of Two Valid Parentheses Strings
- 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.
解析
仍然是递归解法。
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