leetcode117
Populating Next Right Pointers in Each Node II
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
- You may only use constant extra space.
For example,
Given the following binary tree,
1 / \ 2 3 / \ \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL其实之前已经写过一个第一版的题目了,是用队列解决的,所以这次又使用了同样的方法,,竟然成功了,,,,感觉如果用队列的话,就算题目改了点,还是可以成功通过的,下面上代码和第一题的链接,可以参照第一题里我写的一些解释,,,。、
/**
* 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 ;
}
int count = 1;
queue<TreeLinkNode*> qt;
qt.push(root);
while (!qt.empty()) {
TreeLinkNode * temp = qt.front();
qt.pop();
if (temp->left) {
qt.push(temp->left);
}
if (temp->right) {
qt.push(temp->right);
}
count--;
if (count == 0) {
temp->next = NULL;
count = qt.size();
} else {
temp->next = qt.front();
}
}
}
};
第一题:http://blog.csdn.net/guicaisa/article/details/46425693