Skip to content

Latest commit

 

History

History
89 lines (58 loc) · 3.1 KB

0235-lowest-common-ancestor-of-a-binary-search-tree.adoc

File metadata and controls

89 lines (58 loc) · 3.1 KB

235. Lowest Common Ancestor of a Binary Search Tree

{leetcode}/problems/lowest-common-ancestor-of-a-binary-search-tree/[LeetCode - Lowest Common Ancestor of a Binary Search Tree^]

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]

{image_attr}

Example 1:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.

Example 2:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

Note:

  • All of the nodes' values will be unique.

  • p and q are different and both values will exist in the BST.

思路分析

要充分利用二叉搜索树的特性:左大右小,如果根节点大于两个指定节点的值,那么公共祖先就在左子树上;如果根节点小于两个指定节点的值,那么公共祖先就在右子树上;否则就是他们的公共祖先节点。

{image_attr}
{image_attr}
{image_attr}
{image_attr}
{image_attr}
{image_attr}
{image_attr}
一刷
link:{sourcedir}/_0235_LowestCommonAncestorOfABinarySearchTree.java[role=include]
二刷
link:{sourcedir}/_0235_LowestCommonAncestorOfABinarySearchTree_2.java[role=include]

作为这道题的延伸,继续看 236. Lowest Common Ancestor of a Binary Tree

参考资料

  1. 235. 二叉搜索树的最近公共祖先 - 官方题解

  2. 235. 二叉搜索树的最近公共祖先 - 深度优先搜索,清晰图解

  3. 235. 二叉搜索树的最近公共祖先 - 3种解决方式 — 根节点与两个节点的差值相乘,如果小于 0 则节点分布在左右子树上,当前根节点就是公共祖先节点。