{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]
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 nodes2
and8
is6
.
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 nodes2
and4
is2
, 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.
要充分利用二叉搜索树的特性:左大右小,如果根节点大于两个指定节点的值,那么公共祖先就在左子树上;如果根节点小于两个指定节点的值,那么公共祖先就在右子树上;否则就是他们的公共祖先节点。
- 一刷
-
link:{sourcedir}/_0235_LowestCommonAncestorOfABinarySearchTree.java[role=include]
- 二刷
-
link:{sourcedir}/_0235_LowestCommonAncestorOfABinarySearchTree_2.java[role=include]
作为这道题的延伸,继续看 236. Lowest Common Ancestor of a Binary Tree。
-
235. 二叉搜索树的最近公共祖先 - 3种解决方式 — 根节点与两个节点的差值相乘,如果小于
0
则节点分布在左右子树上,当前根节点就是公共祖先节点。