您的位置:首页 > Web前端 > Node.js

LeetCode: Populating Next Right Pointers in Each Node II

2013-04-19 14:48 561 查看
这题关键是要记录下一层第一个节点

/**
* 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:
TreeLinkNode *nextright(TreeLinkNode *root) {
while (root) {
if (root->left) return root->left;
if (root->right) return root->right;
root = root->next;
}
return NULL;
}
void connect(TreeLinkNode *root) {
if (!root) return;
TreeLinkNode *second, *first;
first = root;
second = NULL;
first->next = NULL;
while (first) {
if (first->left) {
if (!second) second = first->left;
if (first->right) first->left->next = first->right;
else first->left->next = nextright(first->next);
}
if (first->right) {
if (!second) second = first->right;
first->right->next = nextright(first->next);
}
first = first->next;
if (!first) {
first = second;
second = NULL;
}
}
}
};


如果可以用extra space,可以用下面这段代码

/**
* 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) {
queue<TreeLinkNode *> S;
if (!root) return;
S.push(root);
S.push(NULL);
while (!S.empty()) {
TreeLinkNode *front = S.front();
S.pop();
if (!front) continue;
front->next = S.front();
if (front->left) S.push(front->left);
if (front->right) S.push(front->right);
if (!S.front()) S.push(NULL);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: