1. 程式人生 > 實用技巧 >[LeetCode] 117. Populating Next Right Pointers in Each Node II

[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 toNULL.

Initially, all next pointers are set toNULL.

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:

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 than6000.
  • -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 題目總結