how do i represent binary search trees in python?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
sillywalkis silly indeed, because exactly the same functionality is a singe-liner external snippet on top of thewalkmethod:and with
walkyou can obtain just about any other functionality on the nodes-in-order stream, while, withsillywalk, you can obtain just about diddly-squat. But, hey, the OP saysyieldis “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 hopingprintisn’t!This is all completely beyond the actual question, on representing BSTs: that question is entirely answered in the
__init__— apayloadattribute to hold the node’s payload,leftandrightattribute to hold eitherNone(meaning, this node has no descendants on that side) or aNode(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 addedinsertjust to show how trivial it is to maintain that constraint,walk(and nowsillywalk) 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.