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

时间:2020-04-28
本文章向大家介绍填充每个节点的下一个右侧节点指针,主要包括填充每个节点的下一个右侧节点指针使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *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.

Follow up:

  • You may only use constant extra space.
  • Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.

Example 1:

Input: root = [1,2,3,4,5,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected 

这道题目的思路:
1. 我们观察 左节点的next 都是根节点右子树 (比如2 的next 是1 的right)
2. 右节点的next都是 自己根节点的next的左子树(比如5的next 是自己的根节点2 的next 即3 的right)
所以有程序:
void dsf(struct Node* root, struct Node* next);
struct Node* connect(struct Node* root) {
    
    dsf(root, NULL);
    return root;
    
}


void dsf(struct Node* root, struct Node* next)
{
    if(root != NULL)
       root->next = next;
    else
        return ;
    dsf(root->left, root->right);
    dsf(root->right, root->next == NULL?NULL:root->next->left);
}

当然我们也可以用模板:

这个题目符合层序遍历

层序遍历的模板:

func connect(root *Node) *Node {
    if root == nil {
        return nil
    }
    pre := root

    for pre.Left != nil {
        parent := pre
        for parent != nil {
            parent.Left.Next = parent.Right //左节点连接右节点
            if parent.Next != nil {
                parent.Right.Next = parent.Next.Left //右节点 连接 邻居左节点
            }
            parent = parent.Next //同层移动
        }
        pre = pre.Left //移到下层
    }
    return root
}

作者:linbingyuan
链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/solution/wo-jiao-mo-ban-liu-by-linbingyuan/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

原文地址:https://www.cnblogs.com/shwzh1990/p/12793521.html