首页 > 代码库 > Leetcode#116 Populating Next Right Pointers in Each Node

Leetcode#116 Populating Next Right Pointers in Each Node

原题地址

 

Populating Next Right Pointers in Each Node II(参见这篇文章)的简化版,代码不变

 

代码:

 1 void connect(TreeLinkNode *root) { 2   queue<TreeLinkNode *> layer; 3  4   layer.push(root); 5   while (!layer.empty()) { 6     queue<TreeLinkNode *> nextLayer; 7     TreeLinkNode *prev = NULL; 8  9     while (!layer.empty()) {10       TreeLinkNode *front = layer.front();11       layer.pop();12       if (!front)13         continue;14       if (prev)15         prev->next = front;16       prev = front;17       nextLayer.push(front->left);18       nextLayer.push(front->right);19     }20     layer = nextLayer;21   }22 }

 

Leetcode#116 Populating Next Right Pointers in Each Node