Javascript Binary Tree

by Geethalakshmi 2010-09-16 21:19:12

Javascript Binary Tree


A binary tree represents data in a tree of nodes. Each node has a value and two children (left and right). In C, this data structure is usually implemented using structures and pointers. This implementation is possible to do in JavaScript using objects and references; however, for smaller trees, there is an easier and quicker way using only one array. The first item of the array will be the head of the tree. Indexes of left and right child nodes if node i can be calculated using the following formula:

leftChild(i) = 2i + 1
rightChild(i) = 2i + 2

This image illustrates the method (courtesy of Wikipedia): Binary tree in an array



As you see, this method isn't exclusive to JavaScript, but it can be very useful when dealing with small trees. You can, for example, write your own helper functions for getting and setting a node's value or children, and traversing the tree, and those methods will be as simple as doing arithmetic calculations and/or for loops. On the other hand, the disadvantage of this method is that wasted space grows as the depth of the tree increases.

Tagged in:

1528
like
0
dislike
0
mail
flag

You must LOGIN to add comments