코딩복습장

LeetCode: SameTree 본문

코딩 테스트/python(파이썬)

LeetCode: SameTree

코복장 2025. 5. 6. 16:09
728x90

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 same value.

 

Example 1:

Input: p = [1,2,3], q = [1,2,3]
Output: true

Example 2:

Input: p = [1,2], q = [1,null,2]
Output: false

Example 3:

Input: p = [1,2,1], q = [1,1,2]
Output: false

 

Constraints:

  • The number of nodes in both trees is in the range [0, 100].
  • -10^4 <= Node.val <= 10^4

 

이 문제는 Tree를 재귀적으로 순회하며 값과 구조가 같은지 확인하는 문제이다. 

 

풀이 방식은 다음과 같다. 

 

1. 두 트리의 값이 모두 없다면 같은 트리기 때문에 True

2. 둘 중에 하나의 값이 없거나 val이 다를 경우 False

3. root부터 sub Tree를 탐색해가는 방식인 1, 2를 계속해서 반복하면 된다.

 

생각보다 코드는 매우 간단하다.

 

 

 


 

구현코드

 

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: Optional[TreeNode]
        :type q: Optional[TreeNode]
        :rtype: bool
        """

        if not q and not p:
            return True

        if not q or not p or p.val != q.val:
            return False

        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

 

728x90

'코딩 테스트 > python(파이썬)' 카테고리의 다른 글

LeetCode: Group Anagrams  (0) 2025.05.22
LeetCode: Symmetric Tree  (2) 2025.05.06
LeetCode: Kth Largest Element in a Stream  (0) 2025.05.06
LeetCode: Relative Ranks  (0) 2025.05.06
LeetCode: 3Sum  (0) 2025.05.05
Comments