LeetCode Populating Next Right Pointers in Each Node II

题目

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

For example,
Given the following binary tree,

         1
       /  \
      2    3
     / \    \
    4   5    7

After calling your function, the tree should look like:

         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL


接上一题,可能有空节点。

bfs,同时连接下一层的非空节点。

由于下一层的点已经连接,只需要保存下一层的开始位置,不需要额外的队列记录,所以空间开销为O(1);


代码:

/**
 * 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) {
        TreeLinkNode *pos,*next_level=root,*next_head=root;	//当前处理位置,下一层处理到位置,下一层头
	    while(next_head!=NULL)	//层序遍历
	    {
		    pos=next_head;
		    next_head=NULL;
			next_level=NULL;
		    while(pos!=NULL)	//搜索下一层
		    {
				if(pos->left!=NULL)	//处理左节点
				{
					if(next_head==NULL)
					{
						next_head=pos->left;
						next_level=next_head;
					}
					else
					{
						next_level->next=pos->left;
						next_level=next_level->next;
					}
				}
				if(pos->right!=NULL)	//处理右节点
				{
					if(next_head==NULL)
					{
						next_head=pos->right;
						next_level=next_head;
					}
					else
					{
						next_level->next=pos->right;
						next_level=next_level->next;
					}
				}
				pos=pos->next;
		    }
	    }
    }
};

你可能感兴趣的:(LeetCode,C++,算法)