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

本文参考代码随想录

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

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
相关推荐
始三角龙7 小时前
LeetCode hoot 100 -- 缺失的第一个正整数
算法·leetcode·职场和发展
战南诚9 小时前
力扣 之 198.打家劫舍
python·算法·leetcode
_日拱一卒10 小时前
LeetCode:105从前序与中序遍历序列构造二叉树
算法·leetcode·职场和发展
ʚ希希ɞ ྀ10 小时前
dp反思与总结
算法·leetcode·动态规划
菜菜的顾清寒11 小时前
力扣Hot100(23)反转链表
算法·leetcode·链表
m0_6294947311 小时前
LeetCode 热题 100-----27. 合并两个有序链表
数据结构·算法·leetcode·链表
水木流年追梦11 小时前
大模型入门-RL基础
开发语言·python·算法·leetcode·正则表达式
人道领域11 小时前
【LeetCode刷题日记】617.合并二叉树(空间换安全,还是原地省内存)
java·数据结构·算法·leetcode
运筹vivo@11 小时前
3043. 最长公共前缀的长度(Leetcode 每日一题)
c++·算法·leetcode·职场和发展·每日一题
csdn_aspnet1 天前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展