本文是在学习中的总结,欢迎转载但请注明出处:http://blog.****.net/pistolove/article/details/48392713
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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
For example, the lowest common ancestor (LCA) of nodes 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a node can be a descendant of itself according to the LCA definition.
思路:
(1)题意为给定一个BST以及该树上两节点,求这两节点的最近公共祖先。
(2)该题比较简单,通过递归很好实现。如果两节点分别分布在根节点的左右子树上,那么它们的最近公共祖先只能是树根;如果两节点同时分部在根节点的相同子树上,则需要分别递归进行判定。
(3)详情见下方代码。希望本文对你有所帮助。
算法代码实现如下:
package leetcode; import leetcode.utils.TreeNode; /** * * @author liqqc * */ public class Lowest_Common_Ancestor_of_a_Binary_Search_Tree { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { // 在树的两边 if (p.val >= root.val && q.val <= root.val) return root; else if (p.val <= root.val && q.val >= root.val) return root; // 在树的一边 左边或右边 else if (p.val < root.val && q.val < root.val) { // 左边 return lowestCommonAncestor(root.left, p, q); } else { // 右边 return lowestCommonAncestor(root.right, p, q); } } }