LeetCode 117. 填充每个节点的下一个右侧节点指针 II(递归&循环)

1. 题目

填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。

初始状态下,所有 next 指针都被设置为 NULL。

在这里插入图片描述
类似题目:LeetCode 116

2. 解题

2.1 递归

左节点:

  • root有左节点和右节点,则左节点的next为右节点

  • root右节点为null,则查找父节点的兄弟节点的最左边子元素

右节点:

  • root右节点不为null,其next为父节点的兄弟节点的最左边子元素

递归:要先构建右子树,再构建左子树,因为寻找父节点的兄弟节点是从左到右遍历的,如果右子树next没接上就遍历,会出错

class Solution {
public:
    Node* connect(Node* root) {
        if(root == NULL)
        	return root;
        if(root->left)
        {
        	if(root->right)
        		root->left->next = root->right;
        	else
        		root->left->next = findchild(root);
        }
        if(root->right)
        	root->right->next = findchild(root);
	    connect(root->right);
    	connect(root->left); 	
        return root;
    }
    Node* findchild(Node* root) 
    {
    	if(root->next == NULL)
    		return NULL;
    	while(root->next)
    	{
    		if(root->next->left)
    			return root->next->left;
    		if(root->next->right)
    			return root->next->right;
    		root = root->next;
    	}
    	return NULL;
    }
};

2.2 queue循环

以下代码也可以解LeetCode 116

class Solution {
public:
    Node* connect(Node* root) {
        if(root == NULL)
        	return root;
        queue<Node*> q;
        q.push(root);
        Node *p;
        int n;
        while(!q.empty())
        {
        	n = q.size();
        	while(n--)
        	{
        		p = q.front();
        		q.pop();
        		if(n)
	        		p->next = q.front();
        		if(p->left)
        			q.push(p->left);
        		if(p->right)
        			q.push(p->right);
        	}	
        }
        return root;
    }
};

2.3 利用next循环

class Solution {
public:
    Node* connect(Node* root) {
        if(root == NULL)
        	return root;
        Node *parent = root, *prev, *tmp;
        while(parent)
        {
        	while(parent && !parent->left && !parent->right)
        		parent = parent->next;//找到第一个有子的节点parent
        	if(parent == NULL)
        		break;
        	prev = NULL;
        	tmp = parent;
        	while(tmp)	//遍历parent层,将其下层连接
        	{
        		if(tmp->left)
        		{
        			if(prev)
        				prev->next = tmp->left;
        			prev = tmp->left;
        		}
        		if(tmp->right)
        		{
        			if(prev)
        				prev->next = tmp->right;
        			prev = tmp->right;
        		}	
        		tmp = tmp->next;
        	}
        	parent = parent->left ? parent->left : parent->right;
        	//parent移向下一层
        }
        return root;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Michael阿明

如果可以,请点赞留言支持我哦!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值