Leetcode(116) Populating Next Right Pointers in Each Node

Description

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:

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.

Example:

img

Note:

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

解法

最开始没看到空间的要求,采用了两个队列按层遍历二叉树得到了结果

具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;

public Node() {}

public Node(int _val,Node _left,Node _right,Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public Node connect(Node root) {
if(root == null){
return null;
}
Queue<Node> currentLevelQueue = new LinkedList<Node>();
Queue<Node> nextLevelQueue = new LinkedList<Node>();
Node tmpNode = root;
currentLevelQueue.offer(root);
while(currentLevelQueue.size() != 0){
tmpNode = currentLevelQueue.poll();
if(tmpNode.left != null){
nextLevelQueue.offer(tmpNode.left);
nextLevelQueue.offer(tmpNode.right);
}
if(currentLevelQueue.size() == 0){
tmpNode.next = null;
Queue<Node> tmpq;
tmpq = currentLevelQueue;
currentLevelQueue = nextLevelQueue;
nextLevelQueue = tmpq;
}
else{
Node nextNode = currentLevelQueue.element();
tmpNode.next = nextNode;
}
}
return root;
}
}