{ "cells": [ { "cell_type": "markdown", "source": [ "Given a binary tree, return the _level order_ traversal of its nodes' values.\n", "(ie, from left to right, level by level).\n", "\n", "For example:\n", "Given binary tree `[3,9,20,null,null,15,7]`,\n", "\n", "\n", "\n", " 3\n", " / \\\n", " 9 20\n", " / \\\n", " 15 7\n", "\n", "\n", "return its level order traversal as:\n", "\n", "\n", "\n", " [\n", " [3],\n", " [9,20],\n", " [15,7]\n", " ]" ], "metadata": {} }, { "outputs": [ { "output_type": "execute_result", "data": { "text/plain": "level_order (generic function with 1 method)" }, "metadata": {}, "execution_count": 1 } ], "cell_type": "code", "source": [ "# @lc code=start\n", "using LeetCode\n", "\n", "function level_order(root::Union{Nothing, TreeNode{Int}})\n", " isnothing(root) && return Int[]\n", " q = TreeNode{Int}[]\n", " q2 = TreeNode{Int}[]\n", " res = Vector{Int}[]\n", " push!(q, root)\n", " while !isempty(q)\n", " push!(res, Int[])\n", " while !isempty(q)\n", " fst = popfirst!(q)\n", " push!(res[end], fst.val)\n", " !isnothing(fst.left) && push!(q2, fst.left)\n", " !isnothing(fst.right) && push!(q2, fst.right)\n", " end\n", " q, q2 = q2, q\n", " end\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 }