Re: [闲聊] 每日leetcode

楼主: dont   2024-10-24 19:52:23
951. Flip Equivalent Binary Trees
## 思路
DFS recursion
- base case: 检查root1跟root2
- no flip: 检查左/左子树 跟 右/右子树
- flip: 检查左/右子树 跟 右/左子树
## Code
```python
class Solution:
def flipEquiv(self, root1: Optional[TreeNode], root2: Optional[TreeNode])
-> bool:
if not root1 and not root2:
return True
if not root1 or not root2:
return False
if root1.val != root2.val:
return False
# not flip
if self.flipEquiv(root1.left, root2.left) and
self.flipEquiv(root1.right, root2.right):
return True
# flip
return self.flipEquiv(root1.left, root2.right) and
self.flipEquiv(root1.right, root2.left)
```

Links booklink

Contact Us: admin [ a t ] ucptt.com