LeetCode 117. Populating Next Right Pointers in Each Node II
Solution1:我的答案
层次遍历
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
if (!root) return;
queue<TreeLinkNode*> q;
q.push(root);
int cur = 1, next = 0;
while (!q.empty()) {
TreeLinkNode* temp = q.front();
q.pop();
if (cur > 1)
temp->next = q.front();
cur--;
if (temp->left) {
q.push(temp->left);
next++;
}
if (temp->right) {
q.push(temp->right);
next++;
}
if (cur == 0) {
cur = next;
next = 0;
}
}
}
};
Solution2:
参考:转载自:http://www.cnblogs.com/grandyang/p/4290148.html
层次遍历,简练的写法值得学习一个!
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
if (!root) return;
queue<TreeLinkNode*> q;
q.push(root);
while (!q.empty()) {
int len = q.size();
for (int i = 0; i < len; ++i) {
TreeLinkNode *t = q.front(); q.pop();
if (i < len - 1) t->next = q.front();
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
}
}
};
【有待理解啊】Solution3:
参考:转载自:http://www.cnblogs.com/grandyang/p/4290148.html
那么下面贴上constant space的解法,这个解法也是用的层序遍历,只不过没有使用queue了,我们建立一个dummy结点来指向每层的首结点的前一个结点,然后指针t用来遍历这一层,我们实际上是遍历一层,然后连下一层的next,首先从根结点开始,如果左子结点存在,那么t的next连上左子结点,然后t指向其next指针;如果root的右子结点存在,那么t的next连上右子结点,然后t指向其next指针。此时root的左右子结点都连上了,此时root向右平移一位,指向其next指针,如果此时root不存在了,说明当前层已经遍历完了,我们重置t为dummy结点,root此时为dummy->next,即下一层的首结点,然后dummy的next指针清空,代码如下:
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
TreeLinkNode *dummy = new TreeLinkNode(0), *t = dummy;
while (root) {
if (root->left) {
t->next = root->left;
t = t->next;
}
if (root->right) {
t->next = root->right;
t = t->next;
}
root = root->next;
if (!root) {
t = dummy;
root = dummy->next;//dummy存为t的起点,当t指向下一层的首结点时,dummy也指了过去??
dummy->next = NULL;
}
}
return;
}
};