/* 树中每个节点如果右边有节点 就放置一个指针指向该节点
* 利用层序遍历 每一层相当于作为一个链表 最左边的节点是头结点 然后穿起来
* 要用记录层次的遍历法 要么记录一个当前层的长度 要么压入一个空的哨兵
* */
class Solution {
public:
Node* connect(Node* root) {
if(!root) return NULL;
queue<Node*> q;
q.push(root);
while(!q.empty()){
int len = q.size();
for(int i=0;i<len;i++){
auto p = q.front();q.pop();
// 除了最后一个节点 都要设置right
if(i!=len-1) p->next = q.front();
if(p->left) q.push(p->left);
if(p->right) q.push(p->right);
}
}
return root;
}
};
Given a binary tree
struct Node { int val; Node *left; Node *right; Node *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
Example: