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.
๋ ํธ๋ฆฌ์ ๋ชจ๋ ๋ ธ๋๊ฐ ๋์ผํ์ง๋ฅผ ๋ฌป๋ ๋ฌธ์ ๋ค.
๋น์ ํ ์๋ฃ๊ตฌ์กฐ๊ธฐ ๋๋ฌธ์ ๋จ์ linear ํ์์ด ๋ถ๊ฐํ๋ค.
dfs, bfs ๋ชจ๋ ์ ์ฉํด๋ณด์.
# 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: TreeNode, q: TreeNode) -> bool:
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
from collections import deque
class Solution:
def isSameNode(self, p,q):
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val:
return False
return True
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
dq = deque([(p, q)])
while dq:
p,q = dq.popleft()
if not self.isSameNode(p,q):
return False
if p:
dq.append((p.left, q.left))
dq.append((p.right, q.right))
return True