Re: [閒聊] 每日leetcode
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)
```
--
https://i.imgur.com/kyBhy6o.jpeg

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 94.156.205.49 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1729770746.A.015.html
討論串 (同標題文章)
完整討論串 (本文為第 1037 之 1548 篇):