и посмотреть медиа
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.
Задача: 865. Smallest Subtree with all the Deepest Nodes Сложность: medium Дан корень бинарного дерева, глубина каждого узла — это кратчайшее расстояние до корня. Верните наименьшее поддерево, которое содержит все самые глубокие узлы в исходном дереве. Узел называется самым глубоким, если у него наибольшая возможная глубина среди всех узлов в дереве. Поддерево узла — это дерево, состоящее из этого узла и всех его потомков. Пример: Input: root = [3,5,1,6,2,0,8,null,null,7,4] Output: [2,7,4] Explanation: We return the node with value 2, colored in yellow in the diagram. The nodes coloured in blue are the deepest nodes of the tree. Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it. 👨💻 Алгоритм: 1⃣В первой фазе используем поиск в глубину (DFS), чтобы аннотировать узлы. Каждый узел будет хранить информацию о своей глубине и о самой большой глубине среди его потомков. 2⃣Во второй фазе также используем DFS для функции answer(node), которая возвращает наименьшее поддерево, содержащее все самые глубокие узлы. Функция сравнивает глубины левых и правых поддеревьев узла для определения наименьшего поддерева. 3⃣Функция answer(node) возвращает поддерево, которое содержит все самые глубокие узлы всего дерева, а не только рассматриваемого поддерева. 😎 Решение: func subtreeWithAllDeepest(root *TreeNode) *TreeNode { depth := map[*TreeNode]int{nil: -1} var dfs func(node, parent *TreeNode) dfs = func(node, parent *TreeNode) { if node != nil { depth[node] = depth[parent] + 1 dfs(node.Left, node) dfs(node.Right, node) } } dfs(root, nil) maxDepth := -1 for _, d := range depth { if d > maxDepth { maxDepth = d } } var answer func(node *TreeNode) *TreeNode answer = func(node *TreeNode) *TreeNode { if node == nil || depth[node] == maxDepth { return node } L := answer(node.Left) R := answer(node.Right) if L != nil && R != nil { return node } if L != nil { return L } return R } return answer(root) } Ставь 👍 и забирай 📚 Базу знаний
Открыть канал и посмотреть медиаOnly registered users can share their opinion.
Be the first to share your impression of this resource!