File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ # https://leetcode.com/problems/same-tree/
2
+
3
+ from typing import Optional
4
+
5
+ # Definition for a binary tree node.
6
+ class TreeNode :
7
+ def __init__ (self , val = 0 , left = None , right = None ):
8
+ self .val = val
9
+ self .left = left
10
+ self .right = right
11
+
12
+ class Solution :
13
+ def isSameTree (self , p : Optional [TreeNode ], q : Optional [TreeNode ]) -> bool :
14
+ """
15
+ [Complexity]
16
+ - TC: O(n)
17
+ - SC: O(height) (call stack)
18
+
19
+ [Approach]
20
+ 재귀적으로 두 tree를 타고 내려가며 확인할 수 있다.
21
+ 각 단계에서 두 tree가 다르다고 판단할 수 있는 조건은
22
+ (1) 한 쪽 node만 None이거나
23
+ (2) 두 node의 값이 다른
24
+ 경우이다.
25
+ """
26
+ # base condition
27
+ if not p and not q :
28
+ return True
29
+
30
+ # not same
31
+ if not p or not q or p .val != q .val :
32
+ return False
33
+
34
+ return self .isSameTree (p .left , q .left ) and self .isSameTree (p .right , q .right )
You can’t perform that action at this time.
0 commit comments