[LeetCode] 117. Populating Next Right Pointers in Each Node II

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.

Follow up:

  • You may only use constant extra space.
  • Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.

 

Example 1:

[LeetCode] 117. Populating Next Right Pointers in Each Node II_第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.

Constraints:

  • The number of nodes in the given tree is less than 6000.
  • -100 <= node.val <= 100

填充每个节点的下一个右侧节点指针 II。题意跟版本一很接近,唯一不同的条件是这次给的树不一定是完美二叉树,中间会有一些节点的缺失。要求还是一样,请不要使用额外空间。

我参考了这个帖子的思路三,太巧妙了。这是一个迭代BFS的做法。他大体的思路如下,创建一个pre node和一个temp node。从root节点开始遍历,如果当前节点有左孩子和右孩子,则temp节点的next指针需要指向这些孩子节点;如果当前节点是有next节点的,则移动到next节点去,temp节点再连到next节点的左右孩子。直观上看,这个操作基本就是同一层的节点往右平移,同时temp节点从左往右连接了下一层所有的孩子节点。最后一步cur = pre.next,是将cur节点移动到下一层的最左边的节点。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public Node connect(Node root) {
 3         // corner case
 4         if (root == null) {
 5             return root;
 6         }
 7 
 8         // normal case
 9         Node cur = root;
10         while (cur != null) {
11             Node pre = new Node();
12             Node temp = pre;
13             while (cur != null) {
14                 if (cur.left != null) {
15                     temp.next = cur.left;
16                     temp = temp.next;
17                 }
18                 if (cur.right != null) {
19                     temp.next = cur.right;
20                     temp = temp.next;
21                 }
22                 cur = cur.next;
23             }
24             // to the next level
25             cur = pre.next;
26         }
27         return root;
28     }
29 }

 

LeetCode 题目总结

你可能感兴趣的:([LeetCode] 117. Populating Next Right Pointers in Each Node II)