\\# start background\n\nI embarked on a journey to seriously skill up in the domain of [programming](https://hackernoon.com/tagged/programming) years ago, and I started out doing tutorials on Codecademy as well as signing up with courses on Udemy. As my work involved quite a bit of travel, I downloaded the tutorials offline into my ipad and studied on the plane. I started out with the intention of learning programming to build useful things, and even though the journey was really tough at every step, I realised that I never knew what the word ‘difficult’ really meant until I immersed myself into data structures and algorithms.\n\nI am a major in Aerospace Engineering, graduated First Class Hons from Singapore. After that I joined Schlumberger as a New Products Engineer, working on oilfield pumps and had stints in in the North Sea installing equipment. Hours were long (16 hour days were common, with weekends usually burnt too), pay was low but the experience was amazing, and I would not trade that for anything else. Till today the survival training doing capsize drills and going down a Norwegian escape chute as well as taking the helicopter to the rig are fond memories, not something people would experience unless they are an oilfield engineer.\n\nAfter that I joined P&G as a researcher working on Hair Care brands, after 2 promotions I started to realize that whilst project management, stakeholder management (making sure everyone you’re working with is happy) and establishing credibility might be important, and actually is the most important anywhere, I was not gaining skills on the job which are required to do what I am super passionate about, which is to ideate, build useful things that solve problems and set up a brand. The environment I was immersed in though, was super great, with supportive colleagues and management. And working in that corporate setting made me realise how much there is to learn about how a company works; how management makes decisions (whether data-based or from the gut (intuition), which is why business is such a beautiful science and also an art) on allocating people and resources and integrating efforts from different departments to build and invigorate brands. Amazing stuff.\n\nI wanted to help management and product managers at all levels of the company make better-informed decisions by providing quick and accurate facts, and this led me to pick up programming to create a scraping and data mining tool for the masses, and this tool has been providing valuable consumer insights to teams working on billion dollar brands like Pantene, Vicks, Tide, Head and Shoulders, SKII, Oral b, etc. The tool is called [www.wheregottext.com](http://www.wheregottext.com) (acronym WGT) (I have set up the authentication so only P&G employees can create an account).\n\nOther than WGT, I have been building a job hunting app and an app for recognising products in the supermarket and showing relevant online ratings and reviews from other consumers so that consumers can make a more informed decision before buying, instead of just talking to the sales reps in the stores, among other things. I have also been involved in Android and iOS app development, which I shall describe another time.\n\nAnyway, enough with the ranting and I will leave more introduction to another post. Till now, one of the more difficult problems I have come across is the question: Given a BST, find a list of lists which can make the BST.\n\n\\# end background\n\nI shall use the example in Cracking the Coding Interview by Gayle Laakmann McDowell to provide my perspective and explanation in hopes that people coming across this problem would not struggle as much as I did when I was trying to find useful explanations online, with no success. I will provide the code in [Python](https://hackernoon.com/tagged/python). The code in the book is written in Java.\n\n!(https://hackernoon.com/hn-images/1*Qi9TNnAqQO9hooG-21mCUA.png)\n\nConsider the binary search tree on the left. We can try to manually list some of the possible arrays that contains elements that could be inserted to form the binary search tree.\n\n\\[20,10,5,15,25\\]\n\n\\[20,10,25,5,15\\]\n\n\\[20, 25,10,15,5\\]\n\n…\n\nNotice that for every subtree (consisting of three nodes) the root must always be inserted first, followed up any order of the children, because the children are at the same level.\n\nMy initial though to solve this problem is to first do a pre-order traversal of all the nodes, and store the nodes into a list. I would then generate a list of lists of all permutations of the elements, thereafter filtering out lists starting with the value 20, and also the condition of 10 coming before 5 and 15 (since 10 must be added first to form the BST). There are many flaws with this thinking. This is a very manual method and if the BST is bigger or if we are not able to visualise the BST in a chart as above, it would be unnecessarily complex to figure out the hierarchy of nodes. We could do a BFS and figure out that 10 must be before 5 and 15, but I would rather follow the textbook method than to implement this.\n\nWe know that we always break down the problem into smaller ones, and then for BSTs we could use recusion to expand a solution to a bigger problem. In the book, two recursion functions are being used. One is called weaveLists, and another is called allSequences which calls weaveLists.\n\nFirst of all, let’s define a Tree class. We need to be able to do insertions and also to get the root.\n\nclass Node: \n def \\_\\_init\\_\\_(self, val): \n self.l = None \n self.r = None \n self.v = val\n\nclass Tree: \n def \\_\\_init\\_\\_(self): \n self.root = None\n\ndef getRoot(self): \n return self.root\n\ndef insert(self, val): \n if(self.root == None): \n self.root = Node(val) \n else: \n self.\\_insert(val, self.root)\n\ndef \\_insert(self, val, node): \n if(val < node.v): \n if(node.l != None): \n self.\\_insert(val, node.l) \n else: \n node.l = Node(val) \n else: \n if(node.r != None): \n self.\\_insert(val, node.r) \n else: \n node.r = Node(val)\n\nThereafter, we want to be able to weave the elements of a subtree. The weaveList function is as follows (I added in comments directly into the code to explain what is happening) :\n\n\\# Note that in the recursion, we are always using the same reference to first, second and prefix lists, and hence operations to modify these lists would have to be done in-place. Any copies would have to be done with the deepcopy function.\n\n\\### EDIT TO CODE BELOW: instead of using result = prefix.copy(), use:\n\nimport copy \nresult = copy.deepcopy(prefix)\n\nSince .copy() is a shallow copy.\n\nThank you to Zhi Yong for pointing that out.\n\n\\# 'first' list shall be referred to as first\\[\\] \n\\# 'second' list shall be referred to as second\\[\\] \n\\# 'prefix' list shall be referred to as prefix\\[\\]\n\ndef weaveLists(first, second, results, prefix): \n # if first or second is an empty list \n if not first or not second: \n # ensuring that result is a CLONE and not a reference to prefix \n result = prefix.copy() ### EDIT HERE TO DEEPCOPY \n # add result to first or/ and second lists \n if first: \n result += first \n if second: \n result += second \n # append the weaved list which is result, to results \n results.append(result) \n return\n\n # add result to first or/ and second lists \n if first: \n result += first \n if second: \n result += second \n # append the weaved list which is result, to results \n results.append(result) \n return\n\n # this would be the method as described in the textbook \n # first, remove and store first element of first\\[\\] \n headFirst = first.pop(0) \n # append to prefix \n prefix.append(headFirst) \n ### add recursive call to operate on first\\[\\] \n weaveLists(first, second, results, prefix) \n # exit when first\\[\\] is empty\n\n # reset prefix for second recursive call below by removing last element \n # IMPT to modify in-place \n del prefix\\[-1\\] \n # reset first\\[\\] for second recursive call below by adding back first element \n # IMPT to modify in-place \n first.insert(0,headFirst)\n\n # do the same thing on the second\\[\\] \n headSecond = second.pop(0) \n prefix.append(headSecond) \n ### add recursive call to operate on first\\[\\] and second\\[\\] \n weaveLists(first, second, results, prefix) \n del prefix\\[-1\\] \n second.insert(0,headSecond)\n\nWe want the weaveList function to operate on subtrees and build up to the entire Tree.\n\nHence, in general we would want weaveList to work on subtree 1 which is in blue, then the entire tree which is green.\n\n!(https://hackernoon.com/hn-images/1*Bjdb-VujcLcLon6Ygcr4aQ.png)\n\nThe code for allSequences is hence (with comments for explanation):\n\ndef allSequences(node): \n # this is the final list of lists we want to output \n results = \\[\\] \n # termination, append \\[\\] so that results will not be empty\\\\ \n # and the nested for loop will still execute since \n # leftSeq == \\[\\[\\]\\] and rightSeq == \\[\\[\\]\\] in termination \n if not node: \n results.append(\\[\\]) \n return results\n\n # prefix will always be root of subtree \n prefix = \\[\\] \n prefix.append(node.v) \n # then represent the left and right subtrees \n leftSeq = allSequences(node.l) \n rightSeq = allSequences(node.r)\n\n # nested for loop and call weaveLists on each list in \n # leftSeq and rightSeq, which are list of lists \n # and each represents results of each subtree \n for left in leftSeq: \n for right in rightSeq: \n # make weaved an empty list, \n # which is results in weaveList \n weaved = \\[\\] \n weaveLists(left, right, weaved, prefix) \n # weaved is list of lists generated by left\\[\\] and right\\[\\] \n # add weaved list of lists to final \n # results list of lists \n results += weaved\n\nreturn results\n\nThe main function to drive the program would be:\n\nif \\_\\_name\\_\\_ == "\\_\\_main\\_\\_":\n\n tree = Tree() \n \n tree.insert(20) \n tree.insert(10) \n tree.insert(25) \n tree.insert(5) \n tree.insert(15)\n\n allSeq = allSequences(tree.getRoot())\n\n for each in allSeq: \n print (each) \n print (len(allSeq))\n\nCopy all the code into one single script and run it to see results. The code is in Python3.\n\nFeel free to reach out for any comments, advice or questions.