872. 叶子相似的树
class Solution(object):
def leafSimilar(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
"""
res1 = []
self.dfs(root1, res1)
res2 = []
self.dfs(root2, res2)
return res1 == res2
# DFS找二叉树的叶子节点
def dfs(self, root, res):
if not root:
return []
elif not root.left and not root.right:
res.append(root.val)
else:
self.dfs(root.left, res)
self.dfs(root.right, res)
return res
DFS:返回二叉树的叶子结点
class Solution(object):
# DFS找二叉树的叶子节点
def dfs(self, root, res):
if not root:
return []
elif not root.left and not root.right:
res.append(root.val)
else:
self.dfs(root.left, res)
self.dfs(root.right, res)
return res