public void connect(TreeLinkNode root)
    {
        if (root == null)
            return;

        TreeLinkNode p = root;
        TreeLinkNode q = null;
        TreeLinkNode nextNode = null;

        while(p != null)
        {
            if (p.left != null)
            {
                if (q != null)
                    q.next = p.left;
                q = p.left;
                if (nextNode == null)
                    nextNode = q;
            }

            if (p.right != null)
            {
                if (q != null)
                    q.next = p.right;
                q = p.right;
                if (nextNode == null)
                    nextNode = q;
            }

            p = p.next;
        }

        connect(nextNode);
    }