简体   繁体   中英

Lowest Common Ancestor of a Binary Search Tree

I understand the algorithm for the iterative approach of finding LCA of a BST. But I do not understand the line below in BOLD. Could anyone please explain to me?

def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        while (root.val - p.val) * (root.val - q.val) > 0:
            root = (root.left, root.right)[p.val > root.val]
        return root

As I understand you need explanation of this line.

root = (root.left, root.right)[p.val > root.val]

It creates tuple with two elements: root.left and root.right, they have index 0 and 1. p.val > root.val is a boolean expression. if is false(for python this is 0) it selects root.left(eg first element in tuple). if it is true(for python this is 1) is selects root.right(eg second element in tuple).

This is because

>>> False == 0
True
>>> True == 1
True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM