Representation of binary Tree Representation of binary Tree
Representation of binary Tree
Representation of binary Tree • There are two ways to represent binary tree in memory. – Linear representation( Array Representation) – Linked Representation
Linear Representation of binary Tree in memory • This is the static representation of the binary tree, so that a block of memory for an array is to be allocated before going to store actual tree in it. • The size of the memory will be restricted as the memory permits. • In this representation the nodes are stored level by level starting from the zero (root) level. • Root node is stored in the first memory location ( as the first element of array) and the remaining nodes are stored using the following rules. • Assume that the array index is starting at 1
Linear Representation of binary Tree in memory(Cont. ) The root node is at location 1 1. PARENT (i) = [i/2] for the node when i=1 there is no parent. 2. LCHILD(i) = 2*i if 2*i>n then i has no left child. 3. RCHILD(i) = 2*i+1 if 2*i+1>n then i has no child
Advantages: • This method benefits from more compact storage and better locality of reference, particularly during a preorder traversal. Limitations: • Wastage of space for some types of binary tree. • Insertion and deletions require potential changes in the array.
Linked representation of binary trees in memory • This is a dynamic representation of a binary tree. The required memory to store an element is allotted at run time. • Elements are stored by using double linked list node structure i. e. the node is having one data part and two references points to left and right side nodes.
Advantages: • Insertion and deletion involve no data movement and no movement of nodes except the rearrangement of pointers. Limitations: • Given a node structure, it is difficult to determine its parent node. • Memory spaces are wasted for storing NULL pointers for the nodes, which have no sub trees.
- Slides: 9