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
完美二叉树的连接

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

被折叠的 条评论
为什么被折叠?



