-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode-116-Populating-Next-Right-Pointers-in-Each-Node.java
More file actions
90 lines (73 loc) · 2.62 KB
/
LeetCode-116-Populating-Next-Right-Pointers-in-Each-Node.java
File metadata and controls
90 lines (73 loc) · 2.62 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
LeetCode: https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
LintCode: http://www.lintcode.com/problem/populating-next-right-pointers-in-each-node/
JiuZhang: http://www.jiuzhang.com/solutions/populating-next-right-pointers-in-each-node/
ProgramCreek: http://www.programcreek.com/2014/05/leetcode-populating-next-right-pointers-in-each-node-java/
Other: http://www.cnblogs.com/yuzhangcmu/p/4041341.html
Analysis:
*/
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if(root == null) return;
TreeLinkNode parent = root;
TreeLinkNode next = root.left;
while(parent != null && next != null){
TreeLinkNode prev = null;
while(parent != null){
if(prev == null){
prev = parent.left;
}else{
prev.next = parent.left;
prev = prev.next;
}
prev.next = parent.right;
prev = prev.next;
parent = parent.next;
}
parent = next;
next = parent.left;
}
}
// 1. BFS (do level order traversal, but add a prev node)
public Node connect(Node root) {
if (root == null) return null;
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()) {
Node prev = null;
int size = queue.size();
for (int i = 0; i < size; i++) {
Node curr = queue.poll();
if (prev != null) {
prev.next = curr;
}
prev = curr;
if (curr.left != null) queue.add(curr.left);
if (curr.right != null) queue.add(curr.right);
curr.next = null;
}
}
return root;
}
// 2. DFS
// https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/37473/My-recursive-solution(Java)
// Space O(1), Time O(N)
public Node connect(Node root) {
if(root == null) return null;
if(root.left != null) {
root.left.next = root.right;
}
if(root.right != null && root.next != null) root.right.next = root.next.left;
connect(root.left);
connect(root.right);
return root;
}
}