leetcode 116填充每个节点的下一个右侧节点指针
time O(n) ,sapce O(n)
/* // Definition for a Node. class Node { public: 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; } }; */ /** 层序遍历,然后每一层左边节点指向右边节点,最后一个节点指向NULL **/ class Solution { public: Node* connect(Node* root) { if(root==NULL||root->left==NULL) return root; queue<Node*>q; q.push(root->left),q.push(root->right); while(!q.empty()){ int k=q.size(); Node* l,*r=q.front(); q.pop(); if(r->left) q.push(r->left),q.push(r->right); for(int i=1;i<k;i++){ l=r,r=q.front();q.pop(); l->next=r; if(r->left) q.push(r->left),q.push(r->right); } } return root; } };