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

本文参考代码随想录

给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:

struct Node {

int val;

Node *left;

Node *right;

Node *next;

}

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

初始状态下,所有 next 指针都被设置为 NULL。

进阶:

你只能使用常量级额外空间。

使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。

思路

前序遍历

python 复制代码
"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""

class Solution:
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
        def traversal(root):
            if not root: return
            if root.left:
                root.left.next = root.right
            if root.right:
                if root.next:
                    root.right.next = root.next.left
                else:
                    root.right.next = None
            traversal(root.left)
            traversal(root.right)
            return root
        return traversal(root)

层序遍历

遍历每一行的时候,如果不是最后一个Node,则指向下一个Node;如果是最后一个Node,则指向nullptr

python 复制代码
"""
# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""

class Solution:
    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
        if not root:
            return
        queue = [root]
        while queue:
            size = len(queue)
            for i in range(size):
                node = queue.pop(0)
                if i == 0:
                    nodePre = node
                else:
                    nodePre.next = node
                    nodePre = node
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            nodePre.next = None
        return root
相关推荐
有一个好名字30 分钟前
力扣-最大连续1的个数III
c++·算法·leetcode
橘颂TA36 分钟前
【剑斩OFFER】算法的暴力美学——力扣 43 题:字符串相乘
数据结构·算法·leetcode·职场和发展·哈希算法·结构与算法
漫随流水42 分钟前
leetcode算法(199.二叉树的右视图)
数据结构·算法·leetcode·二叉树
Vin0sen44 分钟前
leetcode 高频SQL50题
数据库·leetcode
多米Domi0112 小时前
0x3f 第24天 黑马web (安了半天程序 )hot100普通数组
数据结构·python·算法·leetcode
Swift社区2 小时前
LeetCode 468 验证 IP 地址
tcp/ip·算法·leetcode
黎雁·泠崖4 小时前
栈与队列实战通关:3道经典OJ题深度解析
c语言·数据结构·leetcode
AlenTech11 小时前
160. 相交链表 - 力扣(LeetCode)
数据结构·leetcode·链表
sin_hielo11 小时前
leetcode 1161(BFS)
数据结构·算法·leetcode
iAkuya13 小时前
(leetcode)力扣100 34合并K个升序链表(排序,分治合并,优先队列)
算法·leetcode·链表