Skip to content

Commit 69af9ce

Browse files
committed
feat: add same-tree solution
1 parent f4d3a78 commit 69af9ce

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

same-tree/shinsj4653.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,65 @@
11
"""
22
[문제풀이]
33
# Inputs
4+
두 이진 트리의 노드 배열들 p, q
45
56
# Outputs
7+
두 트리가 같은지 다른지 체크
68
79
# Constraints
10+
- The number of nodes in both trees is in the range [0, 100].
11+
- -104 <= Node.val <= 104
812
913
# Ideas
14+
둘 다 bfs?? 때리면 될 것 같은데?
15+
동시에 탐색하면서 다른 노드 나오면 바로 종료
1016
1117
[회고]
18+
풀긴 풀었는데 좀 더 깔금한 풀이가 있을까?
19+
->
1220
1321
"""
1422

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+
1565

serialize-and-deserialize-binary-tree/shinsj4653.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,4 @@
1313
"""
1414

1515

16+

0 commit comments

Comments
 (0)