4
4
5
5
/**
6
6
* 116. Populating Next Right Pointers in Each Node
7
- *
8
- * Given a binary tree
7
+
8
+ Given a binary tree
9
9
10
10
struct TreeLinkNode {
11
11
TreeLinkNode *left;
@@ -27,52 +27,55 @@ You may assume that it is a perfect binary tree (ie, all leaves are at the same
27
27
2 3
28
28
/ \ / \
29
29
4 5 6 7
30
+
30
31
After calling your function, the tree should look like:
31
32
1 -> NULL
32
33
/ \
33
34
2 -> 3 -> NULL
34
35
/ \ / \
35
- 4->5->6->7 -> NULL */
36
+ 4->5->6->7 -> NULL
37
+ */
36
38
37
39
public class _116 {
38
- public static class Solution1 {
39
- //credit: https://discuss.leetcode.com/topic/1106/o-1-space-o-n-complexity-iterative-solution
40
- //based on level order traversal
41
- public void connect (TreeLinkNode root ) {
40
+ public static class Solution1 {
41
+ /**
42
+ * credit: https://discuss.leetcode.com/topic/1106/o-1-space-o-n-complexity-iterative-solution
43
+ * based on level order traversal
44
+ */
45
+ public void connect (TreeLinkNode root ) {
42
46
43
- TreeLinkNode head = null ; //head of the next level
44
- TreeLinkNode prev = null ; //the leading node on the next level
45
- TreeLinkNode curr = root ; //current node of current level
47
+ TreeLinkNode head = null ; //head of the next level
48
+ TreeLinkNode prev = null ; //the leading node on the next level
49
+ TreeLinkNode curr = root ; //current node of current level
46
50
47
- while (curr != null ) {
48
- while (curr != null ) { //iterate on the current level
49
- //left child
50
- if (curr .left != null ) {
51
- if (prev != null ) {
52
- prev .next = curr .left ;
53
- } else {
54
- head = curr .left ;
55
- }
56
- prev = curr .left ;
57
- }
58
- //right child
59
- if (curr .right != null ) {
60
- if (prev != null ) {
61
- prev .next = curr .right ;
62
- } else {
63
- head = curr .right ;
64
- }
65
- prev = curr .right ;
66
- }
67
- //move to next node
68
- curr = curr .next ;
69
- }
70
- //move to next level
71
- curr = head ;
72
- head = null ;
73
- prev = null ;
51
+ while (curr != null ) {
52
+ while (curr != null ) { //iterate on the current level
53
+ //left child
54
+ if (curr .left != null ) {
55
+ if (prev != null ) {
56
+ prev .next = curr .left ;
57
+ } else {
58
+ head = curr .left ;
74
59
}
60
+ prev = curr .left ;
61
+ }
62
+ //right child
63
+ if (curr .right != null ) {
64
+ if (prev != null ) {
65
+ prev .next = curr .right ;
66
+ } else {
67
+ head = curr .right ;
68
+ }
69
+ prev = curr .right ;
70
+ }
71
+ //move to next node
72
+ curr = curr .next ;
75
73
}
74
+ //move to next level
75
+ curr = head ;
76
+ head = null ;
77
+ prev = null ;
78
+ }
76
79
}
77
-
78
- }
80
+ }
81
+ }
0 commit comments