{ "cells": [ { "cell_type": "markdown", "source": [ "Given a binary tree containing digits from `0-9` only, each root-to-leaf path\n", "could represent a number.\n", "\n", "An example is the root-to-leaf path `1->2->3` which represents the number\n", "`123`.\n", "\n", "Find the total sum of all root-to-leaf numbers.\n", "\n", "**Note:** A leaf is a node with no children.\n", "\n", "**Example:**\n", "\n", "\n", "\n", " Input: [1,2,3]\n", " 1\n", " / \\\n", " 2 3\n", " Output: 25\n", " Explanation:\n", " The root-to-leaf path 1->2 represents the number 12.\n", " The root-to-leaf path 1->3 represents the number 13.\n", " Therefore, sum = 12 + 13 = 25.\n", "\n", "**Example 2:**\n", "\n", "\n", "\n", " Input: [4,9,0,5,1]\n", " 4\n", " / \\\n", " 9 0\n", " / \\\n", " 5 1\n", " Output: 1026\n", " Explanation:\n", " The root-to-leaf path 4->9->5 represents the number 495.\n", " The root-to-leaf path 4->9->1 represents the number 491.\n", " The root-to-leaf path 4->0 represents the number 40.\n", " Therefore, sum = 495 + 491 + 40 = 1026." ], "metadata": {} }, { "outputs": [ { "output_type": "execute_result", "data": { "text/plain": "sum_numbers (generic function with 1 method)" }, "metadata": {}, "execution_count": 1 } ], "cell_type": "code", "source": [ "# @lc code=start\n", "using LeetCode\n", "using DataStructures\n", "\n", "function sum_numbers(root::TreeNode)::Int\n", " queue, res = Deque{TreeNode}(), 0\n", "\n", " !isnothing(root) && push!(queue, root)\n", "\n", " while !isempty(queue)\n", " node = popfirst!(queue)\n", " if isnothing(node.left) && isnothing(node.right)\n", " res += node.val\n", " end\n", " if !isnothing(node.left)\n", " node.left.val += node.val * 10\n", " push!(queue, node.left)\n", " end\n", " if !isnothing(node.right)\n", " node.right.val += node.val * 10\n", " push!(queue, node.right)\n", " end\n", " end\n", "\n", " return res\n", "end\n", "# @lc code=end" ], "metadata": {}, "execution_count": 1 }, { "cell_type": "markdown", "source": [ "---\n", "\n", "*This notebook was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*" ], "metadata": {} } ], "nbformat_minor": 3, "metadata": { "language_info": { "file_extension": ".jl", "mimetype": "application/julia", "name": "julia", "version": "1.10.1" }, "kernelspec": { "name": "julia-1.10", "display_name": "Julia 1.10.1", "language": "julia" } }, "nbformat": 4 }