235-Lowest Common Ancestor of a Binary Search Tree

Title: binary sort tree common ancestor

def lowest_CommonAncestor(root,p,q):
    if p.val <root.val > q.val:
        return lowest_CommonAncestor(root.left,p,q)
    if p.val >root.val <q.val:
        return lowest_CommonAncestor(root.right,p,q)

    return root

Note:

Recursive achieved by the characteristics of binary sort tree, if the value of the root node, the value q is larger than p, described p, q are in the left subtree of the root node, the root node recursive traversal left subtree; root value than p, q values ​​are small. Similarly, traversing the right subtree. When the value of p, q on both sides of the root node, the root node of instructions at this time is p, the nearest common node q.

Guess you like

Origin www.cnblogs.com/kingshine007/p/11373062.html