publicvoidconnect(TreeLinkNode root) {if (root ==null) {return; }// use first to denote the 1st node at each levelTreeLinkNode first = root;// use cur to move right and add next pointersTreeLinkNode cur =null;// because we are modifying next level, so need to make sure we have next levelwhile (first.left!=null) {// set cur to starting point cur = first;// if there are right nodes existwhile (cur !=null) {// connect next level's left to right cur.left.next=cur.right;// if not at the end of this levelif (cur.next!=null) {// add the next pointer between 2 sub trees cur.right.next=cur.next.left; }// move cur pointer to next node cur =cur.next; } first =first.left; }}// 2年后写的版本publicvoidconnect(TreeLinkNode root) {if (root ==null) {return; }TreeLinkNode cur = root;TreeLinkNode nextLevel =cur.left;while (nextLevel !=null) {while (cur !=null) {cur.left.next=cur.right;if (cur.next!=null) { cur.right.next=cur.next.left; } cur =cur.next; } cur = nextLevel; nextLevel =cur.left; }}