473,624 Members | 2,216 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to construct a binary-tree using python?

Hi everyone, I'm wondering whether it's possible to construct a
binary-tree using python.
Since python don't have pointer, it can't dynamically allocate memory
like C language.
But some important data structures like linked list, binary-tree and
hash table are closely linked with dynamic memory technology.

Any help that can be provided would be greatly appreciated.

Thanks in advance

May 6 '06 #1
4 24128
hankssong wrote:
Hi everyone, I'm wondering whether it's possible to construct a
binary-tree using python.
Since python don't have pointer, it can't dynamically allocate memory
like C language.
But some important data structures like linked list, binary-tree and
hash table are closely linked with dynamic memory technology.

Its actually very possible to construct a binary tree in python. If you
do some googles searches you'll, in fact find, some implementations .

Its important to remember that python can dynamically make objects on
the fly. Objects are created as references and so you can make tree
nodes whenever you want to

Here are some snippets, I'm not the most advanced coder but its just to
show you that it can be done.

I wouldn't use this code verbatim, its taylored to a project I was doing
at the time, but I hope this helps you get an idea.
class TreeNode:
def __init__(self, nodeData):
self.left = None
self.right = None
[snip - stuff for my project]
class Tree:

def __init__(self):
self.root = None

#assigns the data to a new TreeNode
def addNode(self, inputData):
return TreeNode(inputD ata) #insert is recursive, so when it reaches
its ending point this is called

#this function traverses the tree and finds the spot to add the node
def insertNode(self , inputData, root):
def insertNode(self , inputData, root):
if inputData.build Tag <= root.bTag:
if root.left == None:
root.left = self.addNode(in putData) #left is empty? add
else:
self.insertNode (inputData, root.left) #visit the left subtree
else:
if root.right == None:
root.right = self.addNode(in putData)
else:
self.insertNode (inputData, root.right)
return #root

def findNode(self, nodeToFind, root): #nodeToFind is just a buildTag
string
if root == None:
return None
else:
#btag is something i needed for what I was doing, ignore it
#print "Comparing " + nodeToFind + " and " + root.bTag
if nodeToFind == root.bTag:
return root
elif nodeToFind < root.bTag:
return( self.findNode(n odeToFind, root.left) )
else:
return( self.findNode(n odeToFind, root.right) )


--

Carl J. Van Arsdall
cv*********@mvi sta.com
Build and Release
MontaVista Software

May 6 '06 #2
Depending on what concrete use you have for binary trees, you may want
to consider tuples. What's cool about them is that you get pattern
matching on your tree for free.
x = ((2,4),(5,6))
y, _ = x
y (2, 4) (_,y), _ = x
y 4


Or you could code your own binary tree class subclassing tuple.
.... just a thought.
v.

May 6 '06 #3
I use google and get some detailed info in the page:
http://aspn.activestate.com/ASPN/Coo.../Recipe/286239
Carl J. Van Arsdall ,vdrab, thank for your help!

May 6 '06 #4
Op 2006-05-06, hankssong schreef <so**********@g mail.com>:
Hi everyone, I'm wondering whether it's possible to construct a
binary-tree using python.
Since python don't have pointer, it can't dynamically allocate memory
like C language.
But some important data structures like linked list, binary-tree and
hash table are closely linked with dynamic memory technology.

Any help that can be provided would be greatly appreciated.


You may have a look here:

http://www.pardon-sleeuwaegen.be/antoon/avltree.html

--
Antoon Pardon
May 10 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1384
by: Steven Arnold | last post by:
Is there a more elegant way to construct \ in a string than something like: s = '\\n' result = eval( "'%s'" ) % s Another ugly method would be to build a dict with all the different special letters I want as keys, and their corresponding values as values. Or I could have a huge if/elif structure. I can't make ord work, because while ord( '\n' ) gives me a reasonable integer that I
9
9712
by: Maurizio Penna | last post by:
I, guys. I've embeded an image into a xml file, something like that: <display type="picture" mime="image/png" name = "mosaico6.png"> <!]> </display> Now, I want to display it with a XSL Transformation, but my code don't work: <display>
11
3132
by: Charles T. | last post by:
Hi, I currently writing a serialize/unserialize architecture. The read/write function will read/write from a binary file. My question is is there some sort on defined standart to use when representing data type (int , int32, int64, double, string, etc....) ? Thanks,
18
22594
by: Bern | last post by:
how to specifiy a binary number in c++? hex numbers are specified by 0x prefix
19
4124
by: jeff | last post by:
how do you convert form byte to Int32 while retaining the binary value of the byte array
5
2330
by: Luke Vogel | last post by:
Hi all, Probably a really basic question, but I cant find an answer ... I have an xml file of books something like: <product> <isbn>0-735-61374-5</isbn> <title>Microsoft Visual Basic Step By Step</title> <author>Michael Halvorsen</author> <subject>Programming</subject>
17
3491
by: Anoob | last post by:
Can we consider () unary operator when calling a function, in exps eq. f(), ( 1 + 2). But when we call function f( 10 ) it is a binary operator. Even if we pass f( 10, 20) as we are using , operator there one operand will be there for ()? And Unary operators like !, +, -, ~, ... are said to be having associativity right to left which means that we can write, (but not allowed) 1. 2! 2. !2
5
2611
by: Peter Olcott | last post by:
I created an object that requires access to another objects data, yet have found no good way to pass this data as a parameter because the member function that requires this data must be a binary predicate for std::sort. The only way that I got it to work so far is to make the other object global. Are there any better ways than this? Thanks, Peter Olcott
2
6996
by: Steven T. Hatton | last post by:
What is the best way to read data from a file into a fixed size array of unsigned char? This is a file holding only a SHA1 digest. What I would really like to do is initialize the ifstream with the buffer allocated to hold the data, seekg(ios_base::end) and magically have the data appear in the buffer. I believe something close to this can be done. I might allocate the array: const unsigned LENGTH = 256; unsigned char b;
2
44687
by: sypi | last post by:
Hi, I'd need to construnct an EXEC statement in my script I am pretty much stuck with data conversion. I need to compare a binary variable with a SID value to an actual SID found in ..sysusers. Whe I construct the EXEC statement the whol line has to be string and I need to find a way to use the binary data as string. So far, I tryed to play with CONVERt and CAST, but could not succeed. A simplified version of what I tried to do:
0
8234
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8172
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8677
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8474
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7158
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4174
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2605
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1482
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.