addChild method

void addChild(
  1. TreeNode child
)

Adds a single child to this node and sets its parent property to this.

If child's parent != null, it will be removed from the children of it's old parent before being added to this.

Implementation

void addChild(TreeNode child) {
  // A node can't be neither child of its children nor parent of itself.
  if (child == parent || child == this) return;

  child.parent?.removeChild(child);

  child._parent = this;

  _children.add(child);
}