LeetCode 116. 填充每个节点的下一个右侧节点指针

题目描述

116. 填充每个节点的下一个右侧节点指针

解法:

先用递归解一下,我们的做法是将每两个相邻的结点都连接起来,那就是 n o d e 1. l e f t → n o d e 1. r i g h t node1.left\rightarrow node1.right node1.leftnode1.right n o d e 2. l e f t → n o d e 2. r i g h t node2.left\rightarrow node2.right node2.leftnode2.right n o d e 1. r i g h t → n o d e 2. l e f t node1.right\rightarrow node2.left node1.rightnode2.left

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    Node* connect(Node* root) {
        if (root == nullptr) return root;
        connectTwoNode(root->left, root->right);
        return root;
    }

    void connectTwoNode(Node* node1, Node* node2){
        if (node1 == nullptr || node2 == nullptr) return;

        node1->next = node2;

        connectTwoNode(node1->left, node1->right);
        connectTwoNode(node2->left, node2->right);
        connectTwoNode(node1->right, node2->left);


    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值