Populating Next Right Pointers in Each Node - LeetCode

本文介绍了一种在完美二叉树中填充每个节点的next指针,使其指向其右侧相邻节点的算法实现。该算法利用递归深度优先搜索的方式,通过常数额外空间完成节点间的连接,并确保最右侧节点的next指针设为NULL。

Given a binary tree

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

 

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).

 

For example,
Given the following perfect binary tree,

         1
       /  \
      2    3
     / \  / \
    4  5  6  7

 

After calling your function, the tree should look like:

         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NULL

思路:通过递归,从root节点向下进行DFS。当遍历到一个节点时,如果它有孩子节点,则将左孩子的next指针指向右孩子。

重点是右孩子的next指针该如何处理。在这里,我们每次递归时都向下传递一个指针,即当前节点的next指针。

当我们要处理当前节点的右孩子next指针时,实际上它应该指向当前节点next指针所指向的节点的左孩子。

此外,在递归时还要判断下,二叉树最右侧的节点的next指针都要为NULL。

 1 class Solution {
 2 public:
 3     void dfs(TreeLinkNode *root, TreeLinkNode *parent_next)
 4     {
 5         if (root->left == NULL) return;
 6         root->left->next = root->right;
 7         root->right->next = (parent_next) ? 
 8             parent_next->left : NULL;
 9         dfs(root->left, root->left->next);
10         dfs(root->right, root->right->next);
11     }
12     void connect(TreeLinkNode *root) {
13         if (root == NULL) return;
14         dfs(root, NULL);
15     }
16 };

 

转载于:https://www.cnblogs.com/fenshen371/p/4913657.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值