原题链接: https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/
给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
image.png
解题思路:
- 基于层级遍历的思想,将每层节点行成链表;
- 使用队列来获取每层的节点,遍历每层节点的同时,判断是否是该层的末位节点,如果不是,该节点的next指针指向队列中的第一位节点
Python3代码:
"""
# 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: 'Node') -> 'Node':
if not root:
return root
queue = [root]
while queue:
size = len(queue)
for i in range(size):
node = queue.pop(0)
if i < size-1:
node.next = queue[0]
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return root
"""
# 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: 'Node') -> 'Node':
if not root:
return root
left_most = root
while left_most.left:
node = left_most
while node:
node.left.next = node.right
if node.next:
node.right.next = node.next.left
node = node.next
left_most = left_most.left
return root
网友评论