题目 235 Lowest Common Ancestor of a Binary Tree
因为是binary search tree,因此利用没个节点的值进行二分查找即可复杂度O(h)
class Solution: # @param {TreeNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, root, p, q): if p.val > q.val: p,q = q,p if root.val in [p.val, q.val]: return root if p.val < root.val < q.val: return root elif p.val < root.val and q.val < root.val: return self.lowestCommonAncestor(root.left, p, q) else: return self.lowestCommonAncestor(root.right, p, q)
时间: 2024-10-14 00:00:25