Given a BST and its root, print all sequences of nodes which give rise to the same bst

前端 未结 8 980
半阙折子戏
半阙折子戏 2020-12-13 05:49

Given a BST, find all sequences of nodes starting from root that will essentially give the same binary search tree.

Given a bst, say

  3
 /  \\
1             


        
8条回答
  •  感动是毒
    2020-12-13 06:17

    Note that the question is actually about topological sorting of a tree: find all the possible ways to perform topological sort. That is, we don't care about the specific way the tree was built, what's important is that elements are always added as leaves, never changing the structure of existing nodes. The constraint on the output is that nodes never precede their ancestors - treating the tree as a classic dependency graph.

    But unlike topological sort for a general DAG, there's no need for reference counting here, since this is a tree - the number of references is always 1 or 0.

    Here's a simple Python implementation:

    def all_toposorts_tree(sources, history):
        if not sources:
            print(history)
            return
        for t in sources:
            all_toposorts((sources - {t}) | {t.left, t.right} - {None}, history + [t.v])
    
    all_toposorts_tree({root}, [])
    

    This is question 4.9 in Cracking the Coding Interview, 6th Edition.

提交回复
热议问题