LeetCode Populating Next Right Pointers in Each Node II

本文探讨了如何通过宽度优先搜索(BFS)算法解决复杂二叉树中节点连接的问题,即使存在空节点。通过在不使用额外空间的情况下,仅保存下一层的开始位置,实现对树的层次遍历和节点链接,优化了空间复杂度。详细介绍了算法步骤和代码实现,包括处理左节点、右节点以及更新节点指针的逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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;
		    }
	    }
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值