leetcode 填充每个节点的下一个右侧节点指针 II

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

递归

Node* connect(Node* root) {
    if(root &&(root->left || root->right))
    {
        if(root->left && root->right)
        {
            root->left->next = root->right;
        }
        Node* pretail = root->right ? root->right : root->left;
        
        Node* node = root->next;
        while(node and not(node->left || node->right))
        {
            node = node->next;
        }
        if(node)
        {
            pretail->next = node->left ? node->left : node->right;
        }
        
        //先迭代右子树,把next都确定了,否则会导致next没有子树时,找next的next找不到
        connect(root->right);
        connect(root->left);
    }
    return root;
}

非递归

1.每一层新建一个空节点head,通过head->next来保存每层的第一个节点。
2.新建一个节点tail,用来遍历每层的节点,通过tail->next链接该层所有节点。
3.当每层节点遍历完,通过cur=head->next移到下一层。

在这里插入图片描述

 Node* connect(Node* root) {
        Node* cur = root;
        while(cur)
        {
            Node* head = new Node(-1);
            Node* tail = head;
            while(cur)//层遍历
            {
                if(cur->left) 
                {
                    tail->next = cur->left;
                    tail = tail->next;
                }
                if(cur->right)
                {
                    tail->next = cur->right;
                    tail = tail->next;
                }
                cur = cur->next;
            }
            cur = head->next;//下一层起始
        }
        return root;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值