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:
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:
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 }
题目的followup要求不使用额外空间,所以另外一种做法的思路如下
时间O(n)
空间O(1)
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 Node pre = root; 33 while (pre.left != null) { 34 Node temp = pre; 35 while (temp != null) { 36 temp.left.next = temp.right; 37 if (temp.next != null) { 38 temp.right.next = temp.next.left; 39 } 40 temp = temp.next; 41 } 42 pre = pre.left; 43 } 44 return root; 45 } 46 }
[LeetCode] 116. Populating Next Right Pointers in Each Node
原文:https://www.cnblogs.com/cnoodle/p/13286953.html