原题链接:Lowest Common Ancestor of a Binary Search Tree
本题是二叉查找树。
二叉查找树或者是一棵空树,或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;
(3)左、右子树也分别为二叉查找树;
(4)没有键值相等的节点。
代码如下:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {TreeNode} root
# @param {TreeNode} p
# @param {TreeNode} q
# @return {TreeNode}
def lowestCommonAncestor(self, root, p, q):
if root is None or p is None or q is None:
return None
if (root.val - p.val) * (q.val - root.val) >= 0:
return root
if root.val >= p.val:
return self.lowestCommonAncestor(root.left, p, q)
return self.lowestCommonAncestor(root.right, p, q)
网友评论