и посмотреть медиа
Golang | LeetCode
и посмотреть медиа
LeetCode tasks in Golang. Solutions with code and explanations.
LeetCode tasks in Golang. Solutions with code and explanations.
AI bot for text-to-speech and voice cloning in Telegram. Create audio using neural network quickly and easily.
Channel with solutions to popular LeetCode tasks in Go. Focus on optimized algorithms, efficient memory usage, and idiomatic code. Helps prepare for technical interviews in companies that use Golang.
Задача: 919. Complete Binary Tree Inserter Сложность: medium Полное двоичное дерево - это двоичное дерево, в котором каждый уровень, кроме, возможно, последнего, полностью заполнен, а все узлы расположены как можно дальше влево. Разработайте алгоритм вставки нового узла в полное двоичное дерево, сохраняя его полным после вставки. Реализуйте класс CBTInserter: CBTInserter(TreeNode root) Инициализирует структуру данных корнем полного бинарного дерева. int insert(int v) Вставляет TreeNode в дерево со значением Node.val == val так, что дерево остается полным, и возвращает значение родителя вставленного TreeNode. TreeNode get_root() Возвращает корневой узел дерева. Пример: Input ["CBTInserter", "insert", "insert", "get_root"] [[[1, 2]], [3], [4], []] Output [null, 1, 2, [1, 2, 3, 4]] 👨💻 Алгоритм: 1⃣Инициализация: Проход по дереву и добавление всех узлов в очередь, чтобы отслеживать узлы, у которых есть хотя бы одно пустое место для нового дочернего узла. 2⃣Вставка: Добавление нового узла в первое доступное место слева направо. 3⃣Возвращение корня: Просто возвращает корневой узел. 😎 Решение: package main type TreeNode struct { Val int Left *TreeNode Right *TreeNode } type CBTInserter struct { root *TreeNode deque []*TreeNode } func Constructor(root *TreeNode) CBTInserter { deque := []*TreeNode{} queue := []*TreeNode{root} for len(queue) > 0 { node := queue[0] queue = queue[1:] if node.Left == nil || node.Right == nil { deque = append(deque, node) } if node.Left != nil { queue = append(queue, node.Left) } if node.Right != nil { queue = append(queue, node.Right) } } return CBTInserter{root, deque} } func (this *CBTInserter) Insert(v int) int { node := this.deque[0] newNode := &TreeNode{Val: v} if node.Left == nil { node.Left = newNode } else { node.Right = newNode this.deque = this.deque[1:] } this.deque = append(this.deque, newNode) return node.Val } func (this *CBTInserter) Get_root() *TreeNode { return this.root } Ставь 👍 и забирай 📚 Базу знаний
Открыть канал и посмотреть медиаOnly registered users can share their opinion.
Be the first to share your impression of this resource!