|
1 | 1 | """
|
2 | 2 | [문제풀이]
|
3 | 3 | # Inputs
|
| 4 | +두 이진 트리의 노드 배열들 p, q |
4 | 5 |
|
5 | 6 | # Outputs
|
| 7 | +두 트리가 같은지 다른지 체크 |
6 | 8 |
|
7 | 9 | # Constraints
|
| 10 | +- The number of nodes in both trees is in the range [0, 100]. |
| 11 | +- -104 <= Node.val <= 104 |
8 | 12 |
|
9 | 13 | # Ideas
|
| 14 | +둘 다 bfs?? 때리면 될 것 같은데? |
| 15 | +동시에 탐색하면서 다른 노드 나오면 바로 종료 |
10 | 16 |
|
11 | 17 | [회고]
|
| 18 | +풀긴 풀었는데 좀 더 깔금한 풀이가 있을까? |
| 19 | +-> |
12 | 20 |
|
13 | 21 | """
|
14 | 22 |
|
| 23 | +# Definition for a binary tree node. |
| 24 | +# class TreeNode: |
| 25 | +# def __init__(self, val=0, left=None, right=None): |
| 26 | +# self.val = val |
| 27 | +# self.left = left |
| 28 | +# self.right = right |
| 29 | +from collections import deque |
| 30 | + |
| 31 | + |
| 32 | +class Solution: |
| 33 | + def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: |
| 34 | + def dfs(p_tree, q_tree): |
| 35 | + print('p: ', p_tree) |
| 36 | + print('q: ', q_tree) |
| 37 | + |
| 38 | + if p_tree is not None and q_tree is not None and p_tree.val == q_tree.val: |
| 39 | + print('add left and right') |
| 40 | + return dfs(p_tree.left, q_tree.left) and dfs(p_tree.right, q_tree.right) |
| 41 | + |
| 42 | + if (p_tree == q_tree == None): |
| 43 | + return True |
| 44 | + |
| 45 | + if (p_tree is not None and q_tree is None) or \ |
| 46 | + (p_tree is None and q_tree is not None) or \ |
| 47 | + (p_tree is not None and q_tree is not None and p_tree.val != q_tree.val): |
| 48 | + print("not same!!") |
| 49 | + return False |
| 50 | + |
| 51 | + return dfs(p, q) |
| 52 | + |
| 53 | +# 해설 |
| 54 | +class Solution: |
| 55 | + def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: |
| 56 | + if p is None and q is None: |
| 57 | + return True |
| 58 | + if p is None or q is None or p.val != q.val: |
| 59 | + return False |
| 60 | + return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | + |
15 | 65 |
|
0 commit comments