日野弥生:勉強しよう

LeetCode 872 - 叶子相似的树

发表于2025年03月12日

#树 #二叉树 #深度优先搜索

找到两个树的叶子节点,然后判断叶子节点列表是否相同即可。

class Solution:
    def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
        list1, list2 = [], []
        def getLeafList(root: Optional[TreeNode], lst: list):
            if not root:
                return
            if not root.left and not root.right:
                lst.append(root.val)
            getLeafList(root.left, lst)
            getLeafList(root.right, lst)
        getLeafList(root1, list1)
        getLeafList(root2, list2)
        return list1 == list2

フラッシュタブ:LeetCode

题目链接:https://leetcode.cn/problems/leaf-similar-trees/

上一篇

LeetCode 572 - 二叉树的层平均值

下一篇

LeetCode LCR 44 - 开幕式焰火