Logo

Programming-Idioms

  • Go
  • C++

Idiom #17 Create a Tree data structure

The structure must be recursive. A node may have zero or more children. A node has access to its children nodes, but not to its parent.

type
  TTree = class
    Children: array of TTree;
    Data: TObject;
  end;     
type
generic
  TTree<_T> = class(TObject)
    Children: array of TObject;
    Data: _T;
  end;

type
  TStringTree = specialize TTree<String>;

This Example uses generics
type Tree[L any] struct {
	Label    L
	Children []*Tree[L]
}

The type parameter L is for arbitrary node label data.

A nil *Tree denotes the empty tree.
type Tree struct {
	Key keyType
	Deco valueType
	Children []*Tree
}

keyType should be easily comparable.
valueType is a type of value associated with current node.
Children is a slice of pointers.

Note that in Go you can call methods of pointer type *Tree even on a nil receiver (an empty tree).
#include <vector>
template<typename T>
struct Node{
  T value;
  std::vector<Node<T>> children;
};
typedef struct node_s
{
    int value;
    struct node_s *nextSibling;
    struct node_s *firstChild;
} node_t;

New implementation...