把每个结点的next指针指向其右边结点。注意:
1、要求常数空间复杂度;
2、假设该树是一个完美二叉树(叶子结点在同一层,每个父结点都有两个子结点);
3、所有结点的next指针初始化是NULL。
方法有很多,这里的作法是bfs层次遍历,同时记录每个最右边的结点,每次判断如果碰到的是最右边结点就设置其next指针为null,否则就设置为队列中的front结点。
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(root == NULL)
return;
TreeLinkNode *tag = root, *topNode;
queue<TreeLinkNode*> q;
q.push(root);
while(!q.empty()){
topNode = q.front();
q.pop();
if(topNode != tag){
topNode->next = q.front();
}
else{
tag = topNode->right;
}
if(topNode->left != NULL) q.push(topNode->left);
if(topNode->right != NULL) q.push(topNode->right);
}
}
};