반응형
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반응형
'Computer Science > LeetCode' 카테고리의 다른 글
| [LeetCode] 133. Clone Graph (0) | 2026.02.01 |
|---|---|
| [LeetCode] 647. Palindromic Substrings (0) | 2026.02.01 |
| [LeetCode] 133. Clone Graph (0) | 2026.01.25 |
| 797. All Paths From Source to Target (0) | 2025.09.15 |
| 947. Most Stones Removed with Same Row or Column (0) | 2025.09.14 |