From 1f5a0c23583bc542f1c965873d2a7374589852f8 Mon Sep 17 00:00:00 2001 From: Gyunseo Lee Date: Tue, 16 Jul 2024 01:19:15 +0900 Subject: [PATCH] 2024-07-16 01:19:15 Affected files: .obsidian/workspace.json src/content/blog/leet-code-919-complete-binary tree-inserter.md --- .obsidian/workspace.json | 22 ++--- ...-code-919-complete-binary tree-inserter.md | 92 +++++++++++++++++++ 2 files changed, 103 insertions(+), 11 deletions(-) create mode 100644 src/content/blog/leet-code-919-complete-binary tree-inserter.md diff --git a/.obsidian/workspace.json b/.obsidian/workspace.json index b04bcfb49..7163c7b29 100644 --- a/.obsidian/workspace.json +++ b/.obsidian/workspace.json @@ -13,7 +13,7 @@ "state": { "type": "markdown", "state": { - "file": "src/content/blog/boj-2529-부등호.md", + "file": "src/content/blog/leet-code-74-search-a-2d-matrix.md", "mode": "source", "source": false } @@ -22,16 +22,16 @@ ] }, { - "id": "2b1c3a474105df20", + "id": "c93cbacdb763ad00", "type": "tabs", "children": [ { - "id": "71e0df042bc7a561", + "id": "4077864ed2ae2ddd", "type": "leaf", "state": { "type": "markdown", "state": { - "file": "src/content/blog/boj-1339-단어-수학.md", + "file": "src/content/blog/leet-code-919-complete-binary tree-inserter.md", "mode": "source", "source": false } @@ -103,7 +103,7 @@ "state": { "type": "backlink", "state": { - "file": "src/content/blog/boj-2529-부등호.md", + "file": "src/content/blog/leet-code-919-complete-binary tree-inserter.md", "collapseAll": false, "extraContext": false, "sortOrder": "alphabetical", @@ -120,7 +120,7 @@ "state": { "type": "outgoing-link", "state": { - "file": "src/content/blog/boj-2529-부등호.md", + "file": "src/content/blog/leet-code-919-complete-binary tree-inserter.md", "linksCollapsed": false, "unlinkedCollapsed": true } @@ -143,7 +143,7 @@ "state": { "type": "outline", "state": { - "file": "src/content/blog/boj-2529-부등호.md" + "file": "src/content/blog/leet-code-919-complete-binary tree-inserter.md" } } } @@ -166,15 +166,16 @@ "table-editor-obsidian:Advanced Tables Toolbar": false } }, - "active": "bb9e313e9ec35bc3", + "active": "4077864ed2ae2ddd", "lastOpenFiles": [ - "src/content/blog/boj-1339-단어-수학.md", + "src/content/blog/leet-code-74-search-a-2d-matrix.md", "src/content/blog/boj-2529-부등호.md", + "src/content/blog/leet-code-919-complete-binary tree-inserter.md", + "src/content/blog/boj-1339-단어-수학.md", "src/content/blog/boj-2660-회장뽑기.md", "src/content/blog/boj-2011-암호코드.md", "src/content/blog/leet-code-438-find-all-anagrams-in-a-string.md", "src/content/blog/boj-5525-ioioi.md", - "src/content/blog/leet-code-74-search-a-2d-matrix.md", "src/content/blog/leet-code-1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.md", "src/content/blog/leet-code-64-minimum-path-sum.md", "src/content/blog/boj-6593-상범-빌딩.md", @@ -195,7 +196,6 @@ "src/content/blog/manage-cli-program-version-using-aqua-proj-on-windows.md", "src/content/blog/astro-paper-4.md", "src/content/blog/implementing-a-worker-thread-pool-in-c.md", - "src/content/blog/boj-5014-스타트링크.md", "dist/assets/forrest-gump-quote@900w.jpeg", "dist/assets/forrest-gump-quote.webp.jpg", "dist/_astro/AstroPaper-v4.E8pWr1CH_Zmry1N@1020w.webp", diff --git a/src/content/blog/leet-code-919-complete-binary tree-inserter.md b/src/content/blog/leet-code-919-complete-binary tree-inserter.md new file mode 100644 index 000000000..54dda7b8b --- /dev/null +++ b/src/content/blog/leet-code-919-complete-binary tree-inserter.md @@ -0,0 +1,92 @@ +--- +author: Gyunseo Lee +title: "LeetCode 919: Complete Binary Tree Inserter" +pubDatetime: 2024-07-16T01:16:00+09:00 +modDatetime: 2024-07-16T01:16:00+09:00 +featured: false +draft: false +tags: + - PS + - Algorithms + - Binary-Tree-Traversal + - Binary-Tree + - LeetCode + - BFS +description: 문제를 꼼꼼히 천천히 읽자... +ogImage: "" +--- + +## Table of contents + +## 들어가며 + +걸린 시간: 120분 + +이 문제를 처음 읽었을 때, binary tree가 아닌 binary search tree로 읽어 버린 실수를 하고 말았습니다. +그래서 거의 20분 넘게 삽질을 하다가, complete binary tree라는 것을 깨닫고 다시 처음부터 문제를 접근했습니다. + +## 접근 + +이 문제는 결국 이진 트리를 BFS 방식으로 순회하면 쉽게 해결되는 문제입니다. +그런데 뭔가 계속 삽질을 하게 됐습니다. +그래서 거의 2시간 걸려서 풀었네요. + +## 구현 + +```python +# 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 + +from collections import deque + +class CBTInserter: + def __init__(self, root: Optional[TreeNode]): + self.node_list = [None for _ in range(10000 + 1)] + q = deque() + q.append((root, 0)) + self.node_list[0] = root + while q: + cur_node, cur_idx = q.popleft() + next_node_left = cur_node.left + next_node_right = cur_node.right + + if next_node_left != None: + self.node_list[cur_idx * 2 + 1] = next_node_left + q.append((next_node_left, cur_idx * 2 + 1)) + + + if next_node_right != None: + self.node_list[cur_idx * 2 + 2] = next_node_right + q.append((next_node_right, cur_idx * 2 + 2)) + # print(self.node_list) + self.put_idx = len([*filter(lambda x: x != None, self.node_list)]) + + def insert(self, val: int) -> int: + # print(self.node_list) + self.node_list[self.put_idx] = TreeNode(val) + + # even num (right) + if self.put_idx % 2 == 0: + parent_idx = self.put_idx // 2 - 1 + self.node_list[parent_idx].right = self.node_list[self.put_idx] + # odd num (left) + else: + parent_idx = self.put_idx // 2 + self.node_list[parent_idx].left = self.node_list[self.put_idx] + + self.put_idx += 1 + return self.node_list[parent_idx].val + + def get_root(self) -> Optional[TreeNode]: + return self.node_list[0] + + +# Your CBTInserter object will be instantiated and called as such: +# obj = CBTInserter(root) +# param_1 = obj.insert(val) +# param_2 = obj.get_root() +```