{ "cells": [ { "cell_type": "markdown", "source": [ "Given a binary tree, find the lowest common ancestor (LCA) of two given nodes\n", "in the tree.\n", "\n", "According to the [definition of LCA on\n", "Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): \"The lowest\n", "common ancestor is defined between two nodes p and q as the lowest node in T\n", "that has both p and q as descendants (where we allow **a node to be a\n", "descendant of itself** ).\"\n", "\n", "\n", "\n", "**Example 1:**\n", "\n", "![](https://assets.leetcode.com/uploads/2018/12/14/binarytree.png)\n", "\n", "\n", "\n", " Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1\n", " Output: 3\n", " Explanation: The LCA of nodes 5 and 1 is 3.\n", "\n", "\n", "**Example 2:**\n", "\n", "![](https://assets.leetcode.com/uploads/2018/12/14/binarytree.png)\n", "\n", "\n", "\n", " Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4\n", " Output: 5\n", " Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.\n", "\n", "\n", "**Example 3:**\n", "\n", "\n", "\n", " Input: root = [1,2], p = 1, q = 2\n", " Output: 1\n", "\n", "\n", "\n", "\n", "**Constraints:**\n", "\n", " * The number of nodes in the tree is in the range `[2, 105]`.\n", " * `-109 <= Node.val <= 109`\n", " * All `Node.val` are **unique**.\n", " * `p != q`\n", " * `p` and `q` will exist in the tree." ], "metadata": {} }, { "outputs": [ { "output_type": "execute_result", "data": { "text/plain": "lowest_common_ancestor_236 (generic function with 1 method)" }, "metadata": {}, "execution_count": 1 } ], "cell_type": "code", "source": [ "# @lc code=start\n", "using LeetCode\n", "\n", "function lowest_common_ancestor_236(\n", " root::TreeNode{Int}, p::TreeNode{Int}, q::TreeNode{Int}\n", ")::TreeNode{Int}\n", " function dfs(node::Union{TreeNode{Int},Nothing})\n", " (isnothing(node) || node == p || node == q) && return node\n", " left, right = dfs(node.left), dfs(node.right)\n", " isnothing(left) && isnothing(right) && return nothing\n", " !isnothing(left) && !isnothing(right) && return node\n", " return !isnothing(left) ? left : right\n", " end\n", " return dfs(root)\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 }