Iterative

void connect(TreeLinkNode *root) {

TreeLinkNode p, ph;

if(!root) return;

while(root){

p=NULL;//next level pointer

ph=NULL;//header of next level

for(;root;root=root->next){

if(!ph) ph = root->left!=NULL? root->left : root->right;

if(root->left){

if(p) p->next=root->left;

p=root->left;

}

if(root->right){

if(p) p->next=root->right;

p=root->right;

}

}

root=ph;

}

}

Last updated

Was this helpful?