I am programming a card game for fun to learn solidity. I have noticed that there seems to be a lack of data structures to use apart from dynamic/static arrays & mappings.

For example I have

struct Character { 
    bool engaged;
    string name;
    string charType;
    uint dna;
    uint weaponCounter;
    uint armourCounter;
    uint battleCounter;
    uint16 level;
    CharacterStatistics charStats;  
    mapping (uint => WeaponStats) weapons;  
    mapping (uint => ArmourStats) armour;              
    mapping (uint => BattleStatistics) battleStats;  
/// @notice An array(vector) of Characters. 
Character[] public characters;

/// @notice Dictionaries that get the owners total characters & get a character owner from the characters id.
mapping (uint => address) public characterToOwner;
mapping (address => uint) public ownerCharacterCount;

I can build a data structure that is essentially a vector of characters and some mappings.

But what would be required to introduce a binary tree in solidity, or any other type of tree structure?

1 Answer 1


You'd build a tree like in any other language. Just keep track of child nodes. Here's a simple tree that allows adding nodes but not deleting them:

pragma solidity ^0.4.21;

contract Tree {
    struct Node {
        bytes data;
        uint256 parent;
        uint256[] children;

    Node[] nodes;

    function Tree() public {
        // root node
        nodes.push(Node("", 0, new uint256[](0)));

    function appendChild(uint256 parentID, bytes data) public returns (uint256 newID) {
        newID = nodes.length;

            data: data,
            parent: parentID,
            children: new uint256[](0)


        return newID;

(To support deletion, you might want to use a linked list for the children instead of a simple array.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.