You are given a binary search tree root and two nodes p and q. Find the lowest common ancestor (LCA) of nodes p and q. The lowest common ancestor is defined as the lowest node in root that has both p and q as descendants (where we allow a node to be a descendant of itself). Select the optimal solution in terms of time complexity. If time complexities are same for multiple solutions, select the one with optimal space complexity. Include recursion stack in the space complexity. function lca(root, p, q):    if not root:        return None    left = lca(root.left, p, q)    right = lca(root.right, p, q)    if left and right:        return root    return left if left else right function lca(root, p, q):    if p.val < root.val and q.val < root.val:        return lca(root.left, p, q)    elif p.val > root.val and q.val > root.val:        return lca(root.right, p, q)    else:        return root function lca(root, p, q):    while root:        if p.val < root.val and q.val < root.val:            root = root.left        elif p.val > root.val and q.val > root.val:            root = root.right        else:            return root

icon
Related questions
Question

You are given a binary search tree root and two nodes p and q. Find the lowest common ancestor (LCA) of nodes p and q. The lowest common ancestor is defined as the lowest node in root that has both p and q as descendants (where we allow a node to be a descendant of itself). Select the optimal solution in terms of time complexity. If time complexities are same for multiple solutions, select the one with optimal space complexity. Include recursion stack in the space complexity.

function lca(root, p, q):
    if not root:
        return None
    left = lca(root.left, p, q)
    right = lca(root.right, p, q)
    if left and right:
        return root
    return left if left else right
function lca(root, p, q):
    if p.val < root.val and q.val < root.val:
        return lca(root.left, p, q)
    elif p.val > root.val and q.val > root.val:
        return lca(root.right, p, q)
    else:
        return root
function lca(root, p, q):
    while root:
        if p.val < root.val and q.val < root.val:
            root = root.left
        elif p.val > root.val and q.val > root.val:
            root = root.right
        else:
            return root
AI-Generated Solution
AI-generated content may present inaccurate or offensive content that does not represent bartleby’s views.
steps

Unlock instant AI solutions

Tap the button
to generate a solution