Ch14. Binary search tree (Python) code clarification

#1

Hi all, I am struggling to understand following example code at p.198 EPI Python:

def search_bst(tree, key):        # whether the key present in the tree
return (tree
        if not tree or tree.data == key else search_bst(tree.left, key)
        if key < tree.data              else search_bst(tree.right, key)
)

I know A if condition else B gives A when the condition met, else we get B.
However, above code is hard to get because (1) it has two if s (2) the “if not tree or tree.data == key” part seems convoluted (at least for me). How can I decode this? Could anyone explain the meaning of this?

0 Likes

#2

I ran with trivial cases and now I guess it is the nested ifs, like,
return tree if it is not tree or tree.data == key else ( search left if key < tree.data else search right ). Correct me if I am wrong.

0 Likes