Connect the nodes in the same level

Given a binary tree, link all the nodes in the same level.

C++:
01 void enList(Node** head, Node* cur)
02 {
03     if(cur==NULL)
04         return;
05     if(*head==NULL){
06         cur->prv=cur;
07         cur->next=cur;
08         *head=cur;
09         return;
10     }
11     Node* tmp=(*head)->prv;
12     tmp->next=cur;
13     cur->prv=tmp;
14     (*head)->prv=cur;
15     cur->next=*head;
16 }
17 
18 void treeWalk(Node* head, int level, vector<Node*>& table)
19 {
20     if(head==NULL)
21         return;
22     if(table.size()<=level)
23         table.push_back(NULL);
24     treeWalk(head->lchild,level+1,table);
25     enList(&(table[level]), head);
26     treeWalk(head->rchild,level+1,table);
27 }
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s