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

时间:2020-07-12
本文章向大家介绍[LeetCode] 116. Populating Next Right Pointers in Each Node,主要包括[LeetCode] 116. Populating Next Right Pointers in Each Node使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

You are given a perfect binary tree where all 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 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:

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 than 4096.
  • -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 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13286953.html