File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change
1
+ from typing import Optional
2
+
3
+ # Definition for a binary tree node.
4
+ class TreeNode :
5
+ def __init__ (self , val = 0 , left = None , right = None ):
6
+ self .val = val
7
+ self .left = left
8
+ self .right = right
9
+
10
+ """
11
+ 재귀 풀아
12
+ TC: O(N), 양 트리의 각 노드를 상대로 재귀함수를 딱 1번씩만 호출하기 때문
13
+ SC: O(N), 공간복잡도 = 콜스택의 최대 높이(노드의 수)
14
+ """
15
+ class Solution :
16
+ def isSameTree (self , p : Optional [TreeNode ], q : Optional [TreeNode ]) -> bool :
17
+ # 둘 다 null이면 True 반환
18
+ if not p and not q :
19
+ return True
20
+ # 둘 중 하나면 null이면 False 반환
21
+ if not p or not q :
22
+ return False
23
+ # val이 서로 다르면 탐색 중단, False 반환
24
+ if p .val != q .val :
25
+ return False
26
+ # 현재 node의 val이 같다면, 좌우측 자식 트리도 같은지 확인 -> 재귀 호출
27
+ return self .isSameTree (p .left , q .left ) and self .isSameTree (p .right , q .right )
28
+
29
+
30
+ """
31
+ 스택 풀이
32
+ TC: O(N)
33
+ SC: O(N)
34
+ """
35
+
36
+ class Solution :
37
+ def isSameTree (self , p : Optional [TreeNode ], q : Optional [TreeNode ]) -> bool :
38
+ stack = [(p , q )]
39
+
40
+ while stack :
41
+ p , q = stack .pop ()
42
+ if not p and not q :
43
+ continue
44
+ if not p or not q :
45
+ return False
46
+ if p .val != q .val :
47
+ return False
48
+ stack .append ((p .left , q .left ))
49
+ stack .append ((p .right , q .right ))
50
+ return True
You can’t perform that action at this time.
0 commit comments