public void connect(TreeLinkNode root) {

    TreeLinkNode parent = root;
    TreeLinkNode child = null;
    TreeLinkNode firstChild = null;

    while (parent != null) {

      if (parent.left != null) {
        if (child == null) {
          child = parent.left;
          firstChild = child;
        } else {
          child.next = parent.left;
          child = child.next;
        }
      }

      if (parent.right != null) {
        if (child == null) {
          child = parent.right;
          firstChild = child;
        } else {
          child.next = parent.right;
          child = child.next;
        }

      }

      parent = parent.next;
      if (parent == null) {
        parent = firstChild;
        child = null;
        firstChild = null;
      }
    }
  }