Leetcode :: Same Tree

์ˆ‘์ˆ‘ยท2021๋…„ 5์›” 25์ผ
0

์•Œ๊ณ ๋ฆฌ์ฆ˜

๋ชฉ๋ก ๋ณด๊ธฐ
98/122
post-thumbnail

Problem

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.


Guess

  • ๋‘ ํŠธ๋ฆฌ์˜ ๋ชจ๋“  ๋…ธ๋“œ๊ฐ€ ๋™์ผํ•œ์ง€๋ฅผ ๋ฌป๋Š” ๋ฌธ์ œ๋‹ค.

  • ๋น„์„ ํ˜• ์ž๋ฃŒ๊ตฌ์กฐ๊ธฐ ๋•Œ๋ฌธ์— ๋‹จ์ˆœ linear ํƒ์ƒ‰์ด ๋ถˆ๊ฐ€ํ•˜๋‹ค.

  • dfs, bfs ๋ชจ๋‘ ์ ์šฉํ•ด๋ณด์ž.

Sol 1. DFS (Recursion)

# 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)

Sol 2. BFS (Queue)

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
profile
ํˆด ๋งŒ๋“ค๊ธฐ ์ข‹์•„ํ•˜๋Š” ์‚ฝ์งˆ ์ „๋ฌธ(...) ์ฃผ๋‹ˆ์–ด ๋ฐฑ์—”๋“œ ๊ฐœ๋ฐœ์ž์ž…๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€