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:

116. Populating Next Right Pointers in Each Node

 

思路一:

与上一篇文章相同的思路,使用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==‘’ 表示空字符

相关文章:

  • 2021-09-20
  • 2021-04-24
  • 2021-04-09
  • 2021-11-15
  • 2022-01-20
  • 2022-02-17
  • 2022-02-24
  • 2022-12-23
猜你喜欢
  • 2021-07-25
  • 2021-10-08
相关资源
相似解决方案