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

[LeetCode] 116. Populating Next Right Pointers in Each Node

You are given aperfect binary treewhereall leaves are on the same level, and every parent has two children. The binary tree has the following definition:

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,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect 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 than4096.
  • -1000 <= node.val <= 1000

填充每個節點的下一個右側節點指標。題意是給一個完美二叉樹,請你按照圖示補足所有的next指標。

我這裡給出一個非常直觀的思路,就是BFS層序遍歷。因為是一個完美二叉樹所以可以這樣做。版本二的時候這個方法則不行了。注意這道題在建立queue的時候,用了LinkedList而非Queue。

時間O(n)

空間O(n)

Java實現

 1 /*
 2 // Definition for a Node.
 3 class Node {
4 public int val; 5 public Node left; 6 public Node right; 7 public Node next; 8 9 public Node() {} 10 11 public Node(int _val) { 12 val = _val; 13 } 14 15 public Node(int _val, Node _left, Node _right, Node _next) { 16 val = _val; 17 left = _left; 18 right = _right; 19 next = _next; 20 } 21 }; 22 */ 23 24 class Solution { 25 public Node connect(Node root) { 26 // corner case 27 if (root == null) { 28 return root; 29 } 30 31 // normal case 32 LinkedList<Node> queue = new LinkedList<>(); 33 queue.add(root); 34 while (!queue.isEmpty()) { 35 int size = queue.size(); 36 Node temp = queue.get(0); 37 for (int i = 1; i < size; i++) { 38 temp.next = queue.get(i); 39 temp = queue.get(i); 40 } 41 for (int i = 0; i < size; i++) { 42 temp = queue.remove(); 43 if (temp.left != null) { 44 queue.add(temp.left); 45 } 46 if (temp.right != null) { 47 queue.add(temp.right); 48 } 49 } 50 } 51 return root; 52 } 53 }

LeetCode 題目總結