From ab6622cc01396a21fcde2e5a1cdcc3a27cdd5543 Mon Sep 17 00:00:00 2001 From: jamiebase <100mgml@gmail.com> Date: Sat, 23 May 2026 17:41:32 +0900 Subject: [PATCH 1/2] Add solution for checking if two binary trees are the same --- same-tree/jamiebase.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 same-tree/jamiebase.py diff --git a/same-tree/jamiebase.py b/same-tree/jamiebase.py new file mode 100644 index 0000000000..08b0bd96e1 --- /dev/null +++ b/same-tree/jamiebase.py @@ -0,0 +1,26 @@ +""" +# Approach +재귀를 이용해서 왼쪽, 오른쪽 서브트리의 값을 비교합니다 + +# Complexity +- Time complexity: 노드 개수 N일 때, O(N) +- Space complexity: 트리 높이 H 일때, O(H) +""" + + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: + if not p and not q: + return True + if not p or not q: + return False + if p.val != q.val: + return False + + return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right) From 555369f5ac0d430f694fdbe8d67306adbea3f7ef Mon Sep 17 00:00:00 2001 From: jamiebase <100mgml@gmail.com> Date: Tue, 26 May 2026 12:04:35 +0900 Subject: [PATCH 2/2] add: implement lowest common ancestor for binary search tree --- .../jamiebase.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 lowest-common-ancestor-of-a-binary-search-tree/jamiebase.py diff --git a/lowest-common-ancestor-of-a-binary-search-tree/jamiebase.py b/lowest-common-ancestor-of-a-binary-search-tree/jamiebase.py new file mode 100644 index 0000000000..a91622b097 --- /dev/null +++ b/lowest-common-ancestor-of-a-binary-search-tree/jamiebase.py @@ -0,0 +1,22 @@ +""" +# Approach +BST 의 특징을 이용해서 값의 대소 비교로 공통 조상을 찾습니다. + +# Complexity +- Time complexity: 트리의 높이 H일때, O(H) +- Space complexity: O(1) +""" + + +class Solution: + def lowestCommonAncestor( + self, root: "TreeNode", p: "TreeNode", q: "TreeNode" + ) -> "TreeNode": + cur = root + while cur: + if p.val < cur.val and q.val < cur.val: + cur = cur.left + elif p.val > cur.val and q.val > cur.val: + cur = cur.right + else: + return cur