116. Populating Next Right Pointers in Each Node

本文介绍了一种在完美二叉树中连接每个节点到其右侧相邻节点的方法,通过两种算法实现:广度优先搜索(BFS)和深度优先搜索(DFS)。详细解释了代码实现过程,展示了如何在Python中操作树结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

 

Example:

 

思路一:

与上一篇文章相同的思路,使用BFS遍历树,并在获得每一层的结点后,完成.next指针的指向

代码一:

"""
# Definition for a Node.
class Node:
    def __init__(self, val, left, right, next):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""
class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if root == None:
            return root
        queue = []
        queue.append(root)
        while queue:
            curtmp = []
            nextmp = []
            for node in queue:
                curtmp.append(node)
                if node.left:
                    nextmp.append(node.left)
                if node.right:
                    nextmp.append(node.right)
            queue = nextmp
            for i in range(len(curtmp)-1):
                curtmp[i].next = curtmp[i+1]
            # curtmp[-1].next = None   no necessory
        return root
            
                    
                    

思路二:

使用DFS遍历

代码二:

"""
# Definition for a Node.
class Node:
    def __init__(self, val, left, right, next):
        self.val = val
        self.left = left
        self.right = right
        self.next = next
"""
class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if root == None:
            return root
        if root.left:
            root.left.next = root.right
            if root.next:
                root.right.next = root.next.left
        self.connect(root.left)
        self.connect(root.right)
        return root

注:初始化时,所有结点的.next指针均是指向None的,因此每层末端结点没必要再做指向None的操作。

Pythond的对象的概念:

Python中,万物皆对象,所有的操作都是针对对象的,那什么是对象,5是一个int对象,‘oblong’是一个str对象,异常也是一个对象,抽象一点是,人,猫,够也是一个对象。

数据类型也是对象

Python提供的基本数据类型主要有:布尔类型、整型、浮点型、字符串、列表、元组、集合、字典等

数据类型也可以看做是一个”类“ 
每一种数据类型都是一个对象,也具有其自己的属性和方法

Python中的None与 NULL(即空字符)的区别

了解以上概念,就不难理解None 与null的区别 :
是不同的一种数据类型

判断的时候 均是False

None表示空对象,NULL==‘’ 表示空字符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值