ZhongKuo0228 / study

0 stars 0 forks source link

872. Leaf-Similar Trees #91

Open fockspaces opened 11 months ago

fockspaces commented 11 months ago
  1. DFS 找 sq
  2. 比對 sq 是否相同
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
        def DFS(root, sq):
            if not root:
                return
            if not root.left and not root.right:
                sq.append(root.val)
            DFS(root.left, sq)
            DFS(root.right, sq)
            return sq
        return DFS(root1, []) == DFS(root2, [])
fockspaces commented 11 months ago

把 DFS 寫法簡化後:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
        def DFS(root):
            if not root:
                return []
            if not root.left and not root.right:
                return [root.val]
            return DFS(root.left) + DFS(root.right)
        return DFS(root1) == DFS(root2)