【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



題意:把每一層節點鏈接起來

思路:層次遍歷的思想,將一層的元素全部入隊,然後將本層每個節點的子節點一次全部入隊

class Solution
{
public:
	void connect(TreeLinkNode* root)
	{
		if (root==NULL)
		{
			return;
		}

		TreeLinkNode* tail = root;
		TreeLinkNode* tmp;
		queue<TreeLinkNode*> q;

		q.push(root);
		while (q.size())
		{
			tmp = q.front();
			q.pop();

			if (tmp->left!=NULL)
			{
				q.push(tmp->left);
			}
			if (tmp->right!=NULL)
			{
				q.push(tmp->right);
			}
			
			if(tmp==tail)
			{
				tmp->next = NULL;
				tail = q.back();
			}
			else
			{
				tmp->next = q.front();
			}

		}
	}
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章