[Leetcode]Populating Next Right Pointers in Each Node

本文介绍了一种用于完美二叉树(即所有叶子节点都在同一层且每个父节点都有两个子节点)中连接相邻节点的算法。该算法通过递归方式设置每个节点的next指针指向其右侧相邻节点,若无相邻节点则设置为NULL。实现仅使用常数额外空间。

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

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

注意是完全二叉树!!!!我没有看Note想了半天没想好怎么求。。。。

 1 /**
 2  * Definition for binary tree with next pointer.
 3  * struct TreeLinkNode {
 4  *  int val;
 5  *  TreeLinkNode *left, *right, *next;
 6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     void connect(TreeLinkNode *root) {
12         if(root == NULL)
13         return ;
14         if(root->right!=NULL){
15             root->left->next=root->right;
16             if(root->next!=NULL){
17                 root->right->next=root->next->left;
18                 }
19             }
20         connect(root->left);
21         connect(root->right);
22         
23     }
24 };

 

转载于:https://www.cnblogs.com/desp/p/4338584.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值