码迷,mamicode.com
首页 > 其他好文 > 详细

Populating Next Right Pointers in Each Node

时间:2015-07-09 12:46:18      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/populating-next-right-pointers-in-each-node/

 1 /**
 2  * Definition for binary tree with next pointer.
 3  * struct TreeLinkNode {
 4  *  int val;
 5  *  TreeLinkNode *left, *right, *next;
 6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     void connect(TreeLinkNode *root) {
12         queue<TreeLinkNode *> q;
13         if(root==NULL)
14             return;
15         q.push(root);
16         while(!q.empty())
17         {
18             TreeLinkNode * tail=NULL;
19             queue<TreeLinkNode *> q2;
20             while(!q.empty())
21             {
22                 TreeLinkNode * temp=q.front();
23                 q.pop();
24                 if(temp->left!=NULL)
25                     q2.push(temp->left);
26                 if(temp->right!=NULL)
27                     q2.push(temp->right);
28                 if(tail!=NULL)
29                 {
30                     tail->next=temp;
31                 }
32                 tail=temp;
33             }
34             q=q2;
35         }
36     }
37 };

 

Populating Next Right Pointers in Each Node

标签:

原文地址:http://www.cnblogs.com/aguai1992/p/4632626.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!