Python3解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.
思路:
这个需要用到二叉搜索树的性质,即左子树的值小于根的值,右子树的值大于根的值。
基于以上性质,根据p,q值的大小和根值的大小,就能够判断是在哪边子树;
如果一大一下,则是分别在左右子树,共同祖先就是根子树;
如果同为大,则都在右子树,继续递归调用函数判断右子树是否是共同祖先
如果同为小,则都在左子树,继续递归调用函数判断左子树是否是共同祖先
代码:
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 root == None: 11 return 12 if (p.val <= root.val and q.val >= root.val) or (p.val >= root.val and q.val <= root.val): 13 return root 14 elif (p.val < root.val and q.val < root.val): 15 return self.lowestCommonAncestor( root.left, p, q) 16 elif (p.val > root.val and q.val > root.val): 17 return self.lowestCommonAncestor( root.right, p, q)