Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Tree represented using array

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?

like image 243
Sanjeev Kulkarni N Avatar asked Nov 24 '11 11:11

Sanjeev Kulkarni N


People also ask

How a binary tree represented using an array?

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.

How a binary tree can be represented sequentially or array?

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.

Can a tree be implemented using array?

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.


1 Answers

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  
like image 84
J Yu Avatar answered Oct 24 '22 11:10

J Yu