Computer Science/LeetCode

[LeetCode] 100. Same Tree

LiDARian 2026. 1. 31. 03:42
반응형

https://leetcode.com/problems/same-tree/description/?envType=problem-list-v2&envId=oizxjoit

 

Same Tree - LeetCode

Can you solve this real interview question? Same Tree - Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the

leetcode.com

 

 

두 graph에 대해서 DFS를 해서 node를 list에 넣은 후, 동일한 지 비교하는 것이 가장 간단하다.

 

# 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 isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        cont_p = []
        cont_q = []
        def dfs(node, cont):
            if node is None:
                cont.append(None)
                return
            cont.append(node.val)
            dfs(node.left, cont)
            dfs(node.right, cont)
        
        dfs(p, cont_p)
        dfs(q, cont_q)

        return cont_p == cont_q
반응형