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

本文参考代码随想录

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

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
相关推荐
历程里程碑29 分钟前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django
TracyCoder1232 小时前
LeetCode Hot100(18/100)——160. 相交链表
算法·leetcode
放荡不羁的野指针3 小时前
leetcode150题-滑动窗口
数据结构·算法·leetcode
TracyCoder1234 小时前
LeetCode Hot100(13/100)——238. 除了自身以外数组的乘积
算法·leetcode
Anastasiozzzz4 小时前
LeetCode Hot100 215. 数组中的第K个最大元素
数据结构·算法·leetcode
让我上个超影吧4 小时前
【力扣76】最小覆盖子串
算法·leetcode·职场和发展
求梦8206 小时前
【力扣hot100题】合并两个有序链表(22)
算法·leetcode·链表
踩坑记录6 小时前
leetcode hot100 21.合并两个有序链表 链表 easy
leetcode
IT_Octopus6 小时前
力扣热题100 20. 有效的括号
算法·leetcode
木井巳6 小时前
【递归算法】求根节点到叶节点数字之和
java·算法·leetcode·深度优先