题目要求
Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return true
if and only if the two given trees with head nodes root1
and root2
are leaf-similar.
题目分析及思路
题目给出二叉树的leaf-similar的定义,即要求两棵二叉树按照从左到右的顺序,它们的叶子节点值序列相同。可以定义一个函数,使用递归得到叶子节点值序列,相比遍历多添一个判断条件。
python代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def leafSimilar(self, root1: 'TreeNode', root2: 'TreeNode') -> 'bool':
def order(root):
res = []
if not root:
return res
if not root.left and not root.right:
res.append(root.val)
return res
res.extend(order(root.left))
res.extend(order(root.right))
return res
return order(root1) == order(root2)