Given a binary tree
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 1:
Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Example 2:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree is in the range?
[0, 6000] . -100 <= Node.val <= 100
Follow-up:
- You may only use constant extra space.
- The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
给定一棵二叉树,该二叉树的节点结构除了节点值,左右子节点指针外,还有一个指针next,要求使每一个节点的next指向它所在层的右侧相邻的节点,如果节点已经是那一层的最右节点了那么next就指向空。?
涉及到二叉树层的概念,很自然会想到用水平遍历。二叉树水平遍历最常用的算法就是迭代法(BFS),即使用一个队列,从根节点开始每次把一层的节点放入队列中,在一次循环中,判断当前队列中节点个数(即当前层的节点个数)假设个数为n,依次从队列中取出一直到第n个节点,另外还需用一个指针始终指向当前节点的前一个节点,这样当前节点就是前一个节点在该层的右侧节点,只需把前一个节点的next指向当前节点。另外在处理每一个节点的同时判断其左右子节点是否存在,若存在就把它们放入队列中,这样当前层n个节点都处理完之后,队列中所有节点就是下一层的所有节点(这样就完成了一次迭代)。直到最后队列为空就表示整棵树处理完毕。
class Solution:
def connect(self, root: 'Node') -> 'Node':
if not root:
return None
q = deque([root])
while q:
n = len(q)
pre = None
for i in range(n):
node = q.popleft()
if pre:
pre.next = node
pre = node
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
return root
|