117. Populating Next Right Pointers in Each Node II

本文介绍了一种解决二叉树中填充相邻节点指针的问题的方法,特别针对任何形态的二叉树。通过巧妙利用递归技术,该算法能够在常数额外空间条件下完成任务。

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

  1. 问题描述
    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
        1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL
  2. 解决思路
    116其实就是117的一个特例。所以这里直接贴出117的解决办法就好了。主要是利用递归。一层一层连接,每一层都找到开始的节点,然后用这个节点递归。其实这道题主要是情况讨论题,不难。

  3. 代码
/**
 * 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) {
        helper(root);
    }
    void helper(TreeLinkNode *root) {
        if (!root)
            return;
        TreeLinkNode *cur = root;
        TreeLinkNode *next_pre = NULL,*next_begin = NULL;

        while(cur != NULL) {
            if (!cur->left && !cur->right) {
                cur = cur->next;
            } else if (cur->left && cur->right) {
                if (!next_pre) {
                    cur->left->next = cur->right;
                    next_pre = cur->right;
                    next_begin =cur->left;
                } else {
                    next_pre->next = cur->left;
                    cur->left->next = cur->right;
                    next_pre = cur->right;
                }
                cur = cur->next;
            } else if (!cur->right) {
                if (!next_pre) {
                    next_pre = cur->left;
                    next_begin = cur->left;
                } else {
                    next_pre->next = cur->left;
                    next_pre = cur->left;
                }
                cur = cur->next;
            } else {
                if (!next_pre) {
                    next_pre = cur->right;
                    next_begin = cur->right;
                } else {
                    next_pre->next = cur->right;
                    next_pre = cur->right;
                }
                cur = cur->next;
            }
        }
        helper(next_begin);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值