I was wondering how to save a Binary Tree that I have previously created. Does anyone know how to do it? Thank you so much.
PD: Here there is a link about how to implement a binary tree, I am using this pice od code: http://code.activestate.com/recipes/286239-binary-ordered-tree/
The binary search tree is a special type of tree data structure whose inorder gives a sorted list of nodes or vertices. In Python, we can directly create a BST object using binarytree module. bst() generates a random binary search tree and return its root node.
To insert into a tree we use the same node class created above and add a insert class to it. The insert class compares the value of the node to the parent node and decides to add it as a left node or a right node. Finally the PrintTree class is used to print the tree.
Python TreeNode class A TreeNode is a data structure that represents one entry of a tree, which is composed of multiple of such nodes. The topmost node of a tree is called the “root”, and each node (with the exception of the root node) is associated with one parent node.
One easy solution:
- extend the current class to have a load
and save
method
- add a unique id to each node
- implement to do a top down parsing and save each node to a xml with a structure like that
<node id="mynicelycrafteduniqueid">
<data>...</data>
<leftChild>childuniqueId</leftChild>
<rightChild/> <!-- no right child -->
</node>
You're done (if data is easily serialized at least), first node is your tree root.
don't forget fertilizer and your tree will be reborn even more beautiful
You could implement a small database (such as sqlite3) to have the structure persist.
Example:
Node: {nodeId(PK), [leftChildId](FK), [rightChildId](FK)}
leftChildId, rightChildId references Node;
Similarly to Bruce's answer, you would implement a save
/ load
function.
There are different types of binary trees with different rules that can help simplify deserialization, but basically, just walk the tree and output each node in order, then to re-create it, read in your file and regenerate the structure.
It may be helpful to include markers for each node that indicate whether it's a leaf node (which then tell you whether or not the next element belongs below or above the current node. Alternately, you may want to have a marker that indicates a NULL node, which might help for nodes with a left but not a right branch, for example.
EG:
A
B C
D E F
Could be represented:
A B D - - E - - C - F - -
Or as:
A[B[D,E],C[-,F]]
Reminds me of the Computer Science homework I did back in college.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With