题目描述
Category:Easy Tree
Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).
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.
题目理解
给定两棵树的根节点,判断两棵树的叶子节点序列(从左到右)是否相同。题中进行了举例说明,上图的叶子节点序列是[6, 7, 4, 9, 8].
解题思路
中序遍历
一棵树从左到右的序列应该使用中序遍历,当中序遍历时,如果节点是叶子节点则放入序列之中。
所以判断两棵树的序列是否相等即可。
思路借鉴:https://blog.csdn.net/fuxuemingzhu/article/details/81748617
class Solution:
# Runtime: 36ms 11.66% MemoryUsage: 12.9MB 94.44%
def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
leaves1, leaves2 = [], []
self.inOrder(