美文网首页
LeetCode 117. 填充每个节点的下一个右侧节点指针 I

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

作者: 草莓桃子酪酪 | 来源:发表于2022-08-05 01:53 被阅读0次
题目

给定一个二叉树

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}

填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。初始状态下,所有 next 指针都被设置为 NULL。

例:
输入:root = [1,2,3,4,5,null,7]
输出:[1,#,2,3,#,4,5,7,#]
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。序列化输出按层序遍历顺序(由 next 指针连接),'#' 表示每层的末尾。

方法:递归

使用广度优先遍历的思路,即一层一层的处理

  • curLayer 表示当前层的所有节点,nextLayer 表示下一层的所有节点
  • 遍历当前层的所有节点,因为 next 指针是指向下一个右侧节点的,所以先判断节点的左孩子是否存在,再判断节点的右孩子是否存在,若存在的话,则将其存入 nextLayer
  • 当处理完当前节点层所有节点的孩子节点,判断是否存在下一层,若下一层存在节点的话,则循环将下一层的所有结点按照从左到右的顺序通过 next 指针连接。之后,再调用 BFS 函数,对当前下一层的下一层进行判断
"""
# Definition for a Node.
class Node(object):
    def __init__(self, val=0, left=None, right=None, next=None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""

class Solution(object):
    def connect(self, root):
        if not root:
            return None

        def BFS(curLayer):
            nextLayer = []
            for node in curLayer:
                if node.left:
                    nextLayer.append(node.left)
                if node.right:
                    nextLayer.append(node.right)

            if nextLayer:
                for i in range(len(nextLayer)-1):
                    nextLayer[i].next = nextLayer[i+1]
                BFS(nextLayer)

        BFS([root])
        return root
参考

代码相关:https://leetcode.cn/problems/populating-next-right-pointers-in-each-node-ii/solution/python-zhe-ge-ti-jie-de-si-lu-bu-qing-xi-ni-da-wo-/

相关文章

网友评论

      本文标题:LeetCode 117. 填充每个节点的下一个右侧节点指针 I

      本文链接:https://www.haomeiwen.com/subject/ecodmrtx.html