Tree Data Structures

Overview


Trees are a data structure, consisting of nodes, where each node may have a several nodes related to it. The realitionships can be viewed hierarchically, were a node has one of more child nodes underneath it.

Trees are very useful for categorizing data such that the data at any level can be rolled up to the level above it. Consider expenses in a company. There are many types of expense, for example there is advertising expense and wage expense. But then there are many types of advertising, so you may have television ads or print ads etc.... Likewise, you could break down wage expense as salaries and bonuses.

This process of subdividing a categories into subcategories creates a tree structure.

Example - Advertising Expense


A company's expense is logged in the company's accounting books. Expense is often broken in several categories. In the following, adverising expense is classified as a type of expense, and it can be further sub-divided into categories such as tv ad expense, and print ad expense.

Tree as JSON


The expense tree given above can be written out in code as the following


let tree = {
  name:'expenses',
  children:[
    {
      name:'advertising expense',
      children:[
        {name:'television ad expense'},
        {name:'print ad expense'}
      ]
    },
    {
      name:'wage expense',
      children:[
        {name:'salary expense'},
        {name:'bonus expense'}
      ]
    }
  ]
}
					


Note the tree specified in this way is an example of a Javascript object. It has a name, and it has a property named children, which is an array of other nodes (each with a name and possibly an array of children.)

Trees as Tabular Data


Tree data is not structured like a table, however, it can be saved to a table. This is useful for trees that need to be stored in a relational database.

Consider the following table. Each record has an id, and a parentid which points to the record which is the parent of the current record. (That is the current record, is a child of the parent record.)

Tree Map Module


The tree-map module provides a set of utilities for creating and querying trees. IN particular, it provides a method for reading a table structure from tabular data, as in above.