classSolution{public:voidconnect(TreeLinkNode*root){// Note: The Solution object is instantiated only once and is reused by each test case.
intheight=-1;TreeLinkNode*rootheight=root;while(rootheight!=NULL){height++;rootheight=rootheight->left;}intNumOfNodes=(int)pow(2.0,height+1)-1;TreeLinkNode**LinkNodeArray=newTreeLinkNode*[1000000];intindex=0;LinkNodeArray[index++]=root;intbottom=0;inttop=index;while(true){if(bottom==top)break;for(inti=bottom;i<top;i++){if(LinkNodeArray[i]==NULL)continue;if(i==top-1){LinkNodeArray[i]->next=NULL;if(LinkNodeArray[i]->left!=NULL)LinkNodeArray[index++]=LinkNodeArray[i]->left;if(LinkNodeArray[i]->right!=NULL)LinkNodeArray[index++]=LinkNodeArray[i]->right;}else{LinkNodeArray[i]->next=LinkNodeArray[i+1];if(LinkNodeArray[i]->left!=NULL)LinkNodeArray[index++]=LinkNodeArray[i]->left;if(LinkNodeArray[i]->right!=NULL)LinkNodeArray[index++]=LinkNodeArray[i]->right;}}bottom=top;top=index;}}};