leetcode-python3算法-填充每个节点的下一个右侧节点指针
**1.题目描述:**填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
示例:
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。
2.思路:
- 看到图首先想到就是利用层次遍历,从左到右依次遍历每个节点中的next属性,将其指向下一个节点。
对应代码:
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, left, right, next):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution(object):
def connect(self, root):
"""
:type root: Node
:rtype: Node
"""
if not root:
return
node = [root]
while node:
l =len(node)
for n in range(l):
cur = node.pop(0)
if n < (l-1):
cur.next = node[0]
if cur.left:
node.append(cur.left)
if cur.right:
node.append(cur.right)
return root
2.后面看到答案里有更巧妙的层次遍历。记录下来学习
对应代码:
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
if not root:
return
pre = root
while pre.left:
current = pre # 利用current遍历每一层的节点
while current:
current.left.next = current.right
if current.next:
current.right.next = current.next.left
current = current.next
# 每一层节点遍历完毕后,从上一层的节点的左节点从左到右依次遍历下一层的节点
pre = pre.left
return root
该代码没有像我的方法中那样在遍历时建立一个用于存放节点的列表,而是每行直接从最左边开始,利用了next属性进行遍历。这样的好处不仅节省了空间,也避免弹出节点节约了时间。
3. 递归解法
- 针对于每一个节点node,先判断是否有子节点,如果有,则左右节点都有(题目给的是完美二叉树),那就把该node节点的左节点的next指针指向它的右节点;接着判断该node节点的next指向的是否为空,如果不为空则将它的右节的next指向下一个节点的左节点。
代码如下:
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, left, right, next):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution(object):
def connect(self, root):
"""
:type root: Node
:rtype: Node
"""
if root and root.left:
root.left.next = root.right
if root.next:
root.right.next = root.next.left
else:
root.right.next = None
self.connect(root.left)
self.connect(root.right)
return root
如果觉得对你有帮助的话,右上角,赞一波。谢谢支持!