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].
- -104 <= Node.val <= 104
#https://leetcode.com/problems/same-tree/
'''
1. 아이디어 :
1) DFS로 풀 수 있다
2) Iternation
2. 시간복잡도 :
1) O(n)
2) O(n)
3. 자료구조 :
1) DFS
2) Iteration
'''
# 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:
def dfs(node1,node2):
if not node1 and not node2:
return True
if not node1 or not node2:
return False
if node1.val != node2.val:
return False
return dfs(node1.left,node2.left) and dfs(node1.right, node2.right)
return dfs(p,q)
def isSameTree2(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
def check(node1, node2):
if not node1 and not node2:
return True
if not node1 or not node2:
return False
if node1.val != node2.val:
return False
return True
deq = deque([(p,q)])
print(deq)
while deq:
p, q = deq.popleft()
if not check(p,q):
return False
if p:
deq.append((p.left,q.left))
deq.append((p.right,q.right))
return True
'알고리즘 문제 > Leetcode' 카테고리의 다른 글
235. Lowest Common Ancestor of a Binary Search Tree (0) | 2023.01.22 |
---|---|
572. Subtree of Another Tree (0) | 2023.01.21 |
104. Maximum Depth of Binary Tree (0) | 2023.01.21 |
226. Invert Binary Tree (0) | 2023.01.21 |
543. Diameter of Binary Tree (0) | 2023.01.21 |