简体   繁体   English

二叉搜索树的最低共同祖先

[英]Lowest Common Ancestor of a Binary Search Tree

I understand the algorithm for the iterative approach of finding LCA of a BST.我了解查找 BST 的 LCA 的迭代方法的算法。 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.它创建具有两个元素的元组:root.left 和 root.right,它们的索引为 0 和 1。 p.val > root.val 是 boolean 表达式。 if is false(for python this is 0) it selects root.left(eg first element in tuple).如果为假(对于 python,这是 0)它选择 root.left(例如元组中的第一个元素)。 if it is true(for python this is 1) is selects root.right(eg second element in tuple).如果为真(对于 python,这是 1)选择 root.right(例如元组中的第二个元素)。

This is because这是因为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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