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