Lowest Common Ancestor of a BST

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/

LCA of node 3 and node 5 is node 4

Notion:

root value > its left child and all it's left child's child

root value < its right child and all it's right child's child

simply use this property!

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """

        if p.val < root.val and q.val < root.val:
            return self.lowestCommonAncestor(root.left, p, q)
        if p.val > root.val and q.val > root.val:
            return self.lowestCommonAncestor(root.right, p, q)

        return root

results matching ""

    No results matching ""