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

前端 未结 8 948
半阙折子戏
半阙折子戏 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:00

    here is another concise recursion based easy to understand solution:

    from binarytree import  Node, bst, pprint
    
    def allsequences1(root):
        if not root:
            return None
        lt = allsequences1(root.left)
        rt = allsequences1(root.right)
        ret = []
        if not lt and not rt:
            ret.append([root])
        elif not rt:
            for one in lt:
                ret.append([root]+one)
        elif not lt:
            for two in rt:
                ret.append([root]+two)
        else:
            for one in lt:
                for two in rt:
                    ret.append([root]+one+two)
                    ret.append([root]+two+one)
        return ret
    
    
    
    if __name__=="__main__":
        n = int(input("what is height of tree?"))
        my_bst = bst(n)
        pprint(my_bst)
        seg = allsequences1(my_bst)
        print("All sequences ..1")
        for i in range(len(seq)):
            print("set %d = " %(i+1), end="")
            print(seq[i])
    

提交回复
热议问题