LeetCode116,117. 每个节点的右向指针
code
struct Node {
int val;
Node *left;
Node *right;
Node *next;
Node() {};
Node(int _val Node* _left, Node* _right, Node* _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
class Solution {
public:
Node* connect(Node* root) {
if(!root) return NULL;
if(root->left) root->left->next = root->right;
if(root->right) {
if(root->next)
root->right->next = root->next->left;
else
root->right->next = NULL;
}
connect(root->left);
connect(root->right);
return root;
}
};
class Solution {
public:
Node* connect(Node* root) {
if(!root) return NULL;
queue<Node*> q;
q.push(root);
while(!q.empty()) {
for(int i = 0; i<q.size(); ++i) {
Node* t = q.front(); q.pop();
if(i < q.size()-1)
t->next = q.front();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
}
return root;
}
};