12 Adjacency Graph Builder
Step 13/13 — 13 Tree Builder
01 Create Graph 02 Create Nodes Sources 03 Create Edges Sources 04 Group Nodes 05 Implicit Grouping 06 Configure Styles 07 Create Labels Sources 08 Configure Labels 09 Configure Tags 10 Configure Layout 11 Update Graph 12 Adjacency Graph Builder 13 Tree Builder

# Building a graph with TreeBuilder

In this tutorial step we show how to use TreeBuilder to build a graph from data, where nodes and their children are already available in a tree-like format.

## The data

Consider the following data object, which represents a basic organization chart:

    {
      position: 'Chief Executive Officer',
      name: 'Eric Joplin',
      colleagues: [
        {
          position: 'Chief Executive Assistant',
          name: 'Gary Roberts',
          colleagues: [
            {
              position: 'Senior Executive Assistant',
              name: 'Alexander Burns'
            },
            {
              position: 'Junior Executive Assistant',
              name: 'Linda Newland'
            }
          ]
        },
        {
          position: 'Vice President of Production',
          name: 'Amy Kain',
          colleagues: [
            {
              position: 'Production Supervisor',
              name: 'Kathy Maxwell'
            }
          ]
        }
      ]
    }

Every data object can have an optional `colleagues` property. The `colleagues` property, if available, contains a list of the object’s children as data. The colleagues are of the same type as the data object itself:

    export type OrgChartEntry = {
      position: string
      name: string
      colleagues?: OrgChartEntry[]
    }

## Building the graph

In the first step, we instantiate TreeBuilder and configure a TreeNodesSource:

    const treeBuilder = new TreeBuilder(graph)

    const rootNodesSource = treeBuilder.createRootNodesSource(nodesData)

In the second step, we configure a child NodesSource on the TreeNodesSource:

    // the childDataProvider identifies the property of a node object that contains its child nodes
    rootNodesSource.addChildNodesSource(
      (data) => data.colleagues,
      rootNodesSource
    )

Note that we have used the `rootNodesSource` as the source for the colleagues recursively. The TreeBuilder makes sure no nodes or edges with the same `id` are created twice.

Finally, we add labels to the graph building process by providing a label binding for the NodesSource's NodeCreator.

    rootNodesSource.nodeCreator.createLabelBinding({
      text: (dataItem) => dataItem.name
    })

Note | TreeBuilder supports the same labeling functionality as the GraphBuilder.

See the TreeBuilder Developer’s Guide for a deeper discussion of the TreeBuilder’s functionalities.

Note | Please have a look in this tutorial step’s demo code in `tree-graph-building.ts` and play around with the different ways to import business data.