diff --git a/climbing-stairs/bky373.java b/climbing-stairs/bky373.java new file mode 100644 index 000000000..d5d8b2636 --- /dev/null +++ b/climbing-stairs/bky373.java @@ -0,0 +1,20 @@ +class Solution { + + public int climbStairs(int n) { + if (n == 1) { + return n; + } + int a1 = 1; + int a2 = 2; + for (int i = 3; i < n + 1; i++) { + int a3 = a1 + a2; + a1 = a2; + a2 = a3; + } + return a2; + } +} +/** + * TC: O(N) + * SC: O(1) + */ diff --git a/maximum-depth-of-binary-tree/bky373.java b/maximum-depth-of-binary-tree/bky373.java new file mode 100644 index 000000000..827dd86be --- /dev/null +++ b/maximum-depth-of-binary-tree/bky373.java @@ -0,0 +1,17 @@ +/** + * TC: O(N) + * SC: O(N) + */ +class Solution { + + public int maxDepth(TreeNode root) { + return findMax(root, 0); + } + + public int findMax(TreeNode node, int depth) { + if (node == null) { + return depth; + } + return Math.max(findMax(node.left, depth + 1), findMax(node.right, depth + 1)); + } +} diff --git a/meeting-rooms/bky373.java b/meeting-rooms/bky373.java new file mode 100644 index 000000000..966ce64b0 --- /dev/null +++ b/meeting-rooms/bky373.java @@ -0,0 +1,19 @@ +class Solution { + + public boolean canAttendMeetings(int[][] intervals) { + if (intervals.length == 0) { + return true; + } + Arrays.sort(intervals, (o1, o2) -> o1[0] - o2[0]); + for (int i = 0; i < intervals.length - 1; i++) { + if (intervals[i][1] > intervals[i + 1][0]) { + return false; + } + } + return true; + } +} +/** + * TC: O(nlogn), due to the sorting array. + * SC: O(1) + */ diff --git a/same-tree/bky373.java b/same-tree/bky373.java new file mode 100644 index 000000000..88e3e0c4e --- /dev/null +++ b/same-tree/bky373.java @@ -0,0 +1,11 @@ +/** + * TC: O(N) + * SC: O(N) + */ +class Solution { + public boolean isSameTree(TreeNode p, TreeNode q) { + if (p == null && q == null) return true; + if (p == null || q == null || p.val != q.val) return false; + return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); + } +} diff --git a/subtree-of-another-tree/bky373.java b/subtree-of-another-tree/bky373.java new file mode 100644 index 000000000..7d6a4b2a0 --- /dev/null +++ b/subtree-of-another-tree/bky373.java @@ -0,0 +1,28 @@ +/** + * TC: O(M * N) - N: 메인 트리(root)의 노드 수, M: 서브 트리(subtree)의 노드 수 + * SC: O(M + N) + * - isSubtree() 콜 스택은 최대 N 개 발생할 수 있고, + * - 각각 isSameTree() 콜 스택(M 개)을 더한 값까지 늘어날 수 있다. + * = isSameTree() 콜 스택은 호출 이후 사라지므로, 공간 복잡도는 최대 M + N 이다. + */ +class Solution { + public boolean isSubtree(TreeNode root, TreeNode subRoot) { + if (root == null) { + return false; + } + if (isSameTree(root, subRoot)) { + return true; + } + return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot); + } + + public boolean isSameTree(TreeNode n1, TreeNode n2) { + if (n1 == null || n2 == null) { + return n1 == n2; + } + if (n1.val != n2.val) { + return false; + } + return isSameTree(n1.left, n2.left) && isSameTree(n1.right, n2.right); + } +}