LeetCode 872 Leaf-Similar Trees 解题报告

Posted yao1996

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 872 Leaf-Similar Trees 解题报告相关的知识,希望对你有一定的参考价值。

题目要求

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)

        

 

以上是关于LeetCode 872 Leaf-Similar Trees 解题报告的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 872. Leaf-Similar Trees

Leetcode 872. Leaf-Similar Trees

leetcode 872. 叶子相似的树(Leaf-Similar Trees)

872. Leaf-Similar Trees

872. Leaf-Similar Trees

[leetcode] Leaf-Similar Trees