Skip to content

Commit d00ba34

Browse files
committed
solve(w12): 100. Same Tree
1 parent 17758f5 commit d00ba34

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

same-tree/seungriyou.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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)

0 commit comments

Comments
 (0)