Scribbling

LeetCode: 100. Same Tree 본문

Computer Science/Coding Test

LeetCode: 100. Same Tree

focalpoint 2021. 10. 11. 00:23

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
from collections import deque
class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if p == None and q == None:
            return True
        if p == None and q != None:
            return False
        if p != None and q == None:
            return False
        
        q1, q2 = deque([p]), deque([q])
        while q1:
            n1 = q1.popleft()
            n2 = q2.popleft()
            if n1.val != n2.val:
                return False
            if n1.left != None:
                if n2.left == None:
                    return False
                q1.append(n1.left)
                q2.append(n2.left)
            else:
                if n2.left != None:
                    return False
            if n1.right != None:
                if n1.right == None:
                    return False
                q1.append(n1.right)
                q2.append(n2.right)
            else:
                if n2.right != None:
                    return False
        return True

'Computer Science > Coding Test' 카테고리의 다른 글

LeetCode: 93. Restore IP Addresses  (0) 2021.10.11
LeetCode: 91. Decode Ways  (0) 2021.10.11
LeetCode: 90. Subsets II  (0) 2021.10.10
LeetCode: 88. Merge Sorted Array  (0) 2021.10.09
LeetCode: 98. Validate Binary Search Tree  (0) 2021.10.09