-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path116-populateNextTree.java
More file actions
64 lines (60 loc) · 1.64 KB
/
116-populateNextTree.java
File metadata and controls
64 lines (60 loc) · 1.64 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
// Definition for a Node.
*/
import java.util.*;
// 这个是个完美二叉树,叶子节点均在最后一层
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_116 {
// 层次遍历呗,效果比较差,而且用的不是常数空间
public Node connect_level(Node root) {
if(root == null) return null;
Node pre = null;
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
while(!queue.isEmpty()){
int count = queue.size();
while(count>0) {
Node tmp = queue.poll();
if(pre!=null) {
pre.next = tmp;
}
pre = tmp;
if(tmp.left!=null) {
queue.add(tmp.left);
}
if(tmp.right!=null) {
queue.add(tmp.right);
}
count--;
}
pre.next = null;
pre = null;
}
return root;
}
// 递归解法,从上到下,从左到右的思想
public Node connect_split(Node root) {
if(root == null) return null;
if(root.left != null){
root.left.next = root.right;
}
if(root.next != null && root.right!= null) {
root.right.next = root.next.left;
}
connect_split(root.left);
connect_split(root.right);
return root;
}
}