private function build(array $data)
    {
        $children = array();

        // Create the root node
        $this->nodes[$this->options['rootid']] = $this->createNode(
            array(
                'id'     => $this->options['rootid'],
                'parent' => null,
            )
        );

        foreach ($data as $row) {
            $this->nodes[$row['id']] = $this->createNode($row);
            if (empty($children[$row['parent']])) {
                $children[$row['parent']] = array($row['id']);
            } else {
                $children[$row['parent']][] = $row['id'];
            }
        }

        foreach ($children as $pid => $childids) {
            foreach ($childids as $id) {
                if ($pid == $id) {
                    throw new InvalidParentException(
                        "Node with ID $id references its own ID as parent ID"
                    );
                }
                if (isset($this->nodes[$pid])) {
                    $this->nodes[$pid]->addChild($this->nodes[$id]);
                } else {
                    throw new InvalidParentException(
                        "Node with ID $id points to non-existent parent with ID $pid"
                    );
                }
            }
        }
    }