题目描述:
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.
代码实现:
1 # Definition for a binary tree node. 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution: 9 def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 10 if p.val < root.val and q.val < root.val: 11 return self.lowestCommonAncestor(root.left, p, q) # 在一个函数中调用自身时,必须要加self 12 elif p.val > root.val and q.val > root.val: 13 return self.lowestCommonAncestor(root.right, p, q) 14 else: 15 return root
分析:
二叉树和二叉搜索树的区别见博客:https://blog.csdn.net/u012292754/article/details/87474802
在二叉搜索树中,左子树上所有节点的值均小于它的根节点的值,右子树中所有节点的值均大于它的根节点的值。
这是一条非常有用的性质,相当于事先对二叉树做了一定的排序。
因此在二叉搜索树中,任意两个节点与根节点之间的位置关系只能有以下三种情况:
第一种情况:这两个节点都在根节点的左子树中(即p.val < root.val and q.val < root.val),此时只要继续深入根节点的左子树中查找即可;
第二种情况:这两个节点都在根节点的右子树中(即p.val > root.val and q.val > root.val),此时只要继续深入根节点的右子树中查找即可;
第三种情况:这两个节点有一个是根节点或这两个节点横跨在根节点的两侧(一个在左子树中,一个在右子树中),此时最近公共祖先必为根节点本身。
以上三种情况即为上述代码的实现思路。