represent binary search trees in python

2024/9/24 22:33:30

how do i represent binary search trees in python?

Answer
class Node(object):def __init__(self, payload):self.payload = payloadself.left = self.right = 0# this concludes the "how to represent" asked in the question.  Once you# represent a BST tree like this, you can of course add a variety of# methods to modify it, "walk" over it, and so forth, such as:def insert(self, othernode):"Insert Node `othernode` under Node `self`."if self.payload <= othernode.payload:if self.left: self.left.insert(othernode)else: self.left = othernodeelse:if self.right: self.right.insert(othernode)else: self.right = othernodedef inorderwalk(self):"Yield this Node and all under it in increasing-payload order."if self.left:for x in self.left.inorderwalk(): yield xyield selfif self.right:for x in self.right.inorderwalk(): yield xdef sillywalk(self):"Tiny, silly subset of `inorderwalk` functionality as requested."if self.left:self.left.sillywalk()print(self.payload)if self.right:self.right.sillywalk()

etc, etc -- basically like in any other language which uses references rather than pointers (such as Java, C#, etc).

Edit:

Of course, the very existence of sillywalk is silly indeed, because exactly the same functionality is a singe-liner external snippet on top of the walk method:

for x in tree.walk(): print(x.payload)

and with walk you can obtain just about any other functionality on the nodes-in-order stream, while, with sillywalk, you can obtain just about diddly-squat. But, hey, the OP says yield is "intimidating" (I wonder how many of Python 2.6's other 30 keywords deserve such scare words in the OP's judgment?-) so I'm hoping print isn't!

This is all completely beyond the actual question, on representing BSTs: that question is entirely answered in the __init__ -- a payload attribute to hold the node's payload, left and right attribute to hold either None (meaning, this node has no descendants on that side) or a Node (the top of the sub-tree of descendants on the appropriate side). Of course, the BST constraint is that every left descendant of each node (if any) has a payload less or equal than that of the node in question, every right one (again, if any) has a greater payload -- I added insert just to show how trivial it is to maintain that constraint, walk (and now sillywalk) to show how trivial it is to get all nodes in increasing order of payloads. Again, the general idea is just identical to the way you'd represent a BST in any language which uses references rather than pointers, like, for example, C# and Java.

https://en.xdnf.cn/q/71650.html

Related Q&A

Python os.path.commonprefix - is there a path oriented function?

So I have this python code:print os.path.commonprefix([rC:\root\dir,rC:\root\dir1])Real ResultC:\root\dirDesired resultC:\rootQuestion 1Based on os.path.commonprefix documentation: Return the longest p…

Importing Stripe into Django - NameError

I cant seem to figure out how to import Stripe into my Django project. Im running Python 2.7.3 and I keep receiving NameError at /complete/ global name. stripe is not defined.Even when I just open up T…

getting line-numbers that were changed

Given two text files A,B, what is an easy way to get the line numbers of lines in B not present in A? I see theres difflib, but dont see an interface for retrieving line numbers

How to subclass a subclass of numpy.ndarray

Im struggling to subclass my own subclass of numpy.ndarray. I dont really understand what the problem is and would like someone to explain what goes wrong in the following cases and how to do what Im t…

How to ignore an invalid SSL certificate with requests_html?

So basically Im trying to scrap the javascript generated data from a website. To do this, Im using the Python library requests_html. Here is my code :from requests_html import HTMLSession session = HTM…

Fabric asks for root password

I am using Fabric to run the following:def staging():""" use staging environment on remote host"""env.user = ubuntuenv.environment = stagingenv.hosts = [host.dev]_setup_pa…

Beautifulsoup results to pandas dataframe

The below code returns me a table with the following resultsr = requests.get(url) soup = bs4.BeautifulSoup(r.text, lxml)mylist = soup.find(attrs={class: table_grey_border}) print(mylist)results - it st…

XGBoost CV and best iteration

I am using XGBoost cv to find the optimal number of rounds for my model. I would be very grateful if someone could confirm (or refute), the optimal number of rounds is: estop = 40res = xgb.cv(params, d…

Whats the correct way to implement a metaclass with a different signature than `type`?

Say I want to implement a metaclass that should serve as a class factory. But unlike the type constructor, which takes 3 arguments, my metaclass should be callable without any arguments:Cls1 = MyMeta()…

Python -- Regex -- How to find a string between two sets of strings

Consider the following:<div id=hotlinklist><a href="foo1.com">Foo1</a><div id=hotlink><a href="/">Home</a></div><div id=hotlink><a…