I am not so familiar with trees.
How is a tree stored in memory? what is the data structure type used for storing it?
As a string?linked list? stack (!)?
Or is there some kind of data storage model for trees?
Computer Science Stack Exchange is a question and answer site for students, researchers and practitioners of computer science. It only takes a minute to sign up.
Sign up to join this communityI am not so familiar with trees.
How is a tree stored in memory? what is the data structure type used for storing it?
As a string?linked list? stack (!)?
Or is there some kind of data storage model for trees?
Usually it's stored as an adjacency list. Which is basically a linked list for every single node. So the linked list of a node u
contains every node v
such that (u,v)
is a valid edge of the tree.
The adjacency list of this tree would be:
1 ->
3 -> 1, 4
4 ->
5 -> 3, 8
7 ->
8 -> 7, 10
10 ->
It can also be stored using an adjacency matrix. But that's used when the nodes of the tree are less (since it requires more memory). Adjacency list is better for sparse graphs.
the simplest data representation is Nodes and Links; so a list of Nodes such as 1,2,3,4,5, and a list of links such as 1:2, 1:3, 2:4, 2:5 would represent the tree below:
1
/ \
2 3
/ \
4 5
This data representation also allows additional meta-data to be defined and stored at any of the elements [ie Nodes], or relationships [ ie Links] For example: Age of a node can be added as an Attribute. or PostalAdress of Node can be added as a set of attributes [ie Struct] Beyond that Nodes can be typed, and Links constrained or defined to link certain types only - and hence may carry different set of attributes depending on type of link or types of Nodes joined by that type of link. Traversing the tree is following it from any node in any direction . In reverse directions we would optimize by storing the Link 1:2 as well as the alt-Link 2:1 .
It depends on what data structure you want to represent it with.
I'll illustrate how it's represented and how it's stored in memory for a linked list implementation.
Linked-list representation of the tree on the left.
The left link points to the first node in the linked list of its children
It's clear the root node has three children, so the left link point to its first child, whose right link points to the 2nd and 3rd children, and so for the other sub-tress.
Right links of nodes point to siblings
The right link of the first child points to its next siblings and so on (am considering from left to right).
That's how they are stored in memory for this implementation. And hence the binary tree can be traverse. eg, in-order (visit the left sub-tree, then the parent node, and then the right sub-tree) this is done recursively.