Consider the following array, which is claimed to have represented a binary tree:
[1, 2, 5, 6, -1, 8, 11]
Given that the index with value -1 indicates the root element, I've below questions:
a) How is this actually represented?
Should we follow below formulae (source from this link) to figure out the tree? Three simple formulae allow you to go from the index of the parent to the index of its children and vice versa:
* if index(parent) = N, index(left child) = 2*N+1
* if index(parent) = N, index(right child) = 2*N+2
* if index(child) = N, index(parent) = (N-1)/2 (integer division with truncation)
If we use above formulae, then index(root) = 3, index(left child) = 7, which doesn't exist.
b) Is it important to know whether it's a complete binary tree or not?
Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root.
Sequential representationThe sequential representation uses an array for the storage of tree elements. The number of nodes a binary tree has defines the size of the array being used. The root node of the binary tree lies at the array's first index.
You've seen two approaches to implementing a sequence data structure: either using an array, or using linked nodes. We extended our idea of linked nodes to implement a tree data structure. It turns out we can also use an array to represent a tree.
N=0 must be the root node since by the rules listed, it has no parent. 0 cannot be created from either of the expressions (2*N + 1) or (2*N + 2), assuming no negative N.
Note, index is not the value stored in the array, it is the place in the array. For [1, 2, 5, 6, -1, 8, 11] Index 0 = 1 Index 1 = 2 Index 2 = 5, etc.
If it is a complete tree, then -1 is a valid value and tree is
1
/ \
2 5
/ \ / \
6 -1 8 11
-1 could also be a "NULL" pointer, indicating no value exists at that node.
So the Tree would look like
1
/ \
2 5
/ / \
6 8 11
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