File tree Expand file tree Collapse file tree 2 files changed +66
-0
lines changed
Algorithms/Populating Next Right Pointers in Each Node Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Source : https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
2
+ // Author : Han Zichi
3
+ // Date : 2016-08-29
4
+ // Note : You may only use constant extra space
5
+
6
+ /**
7
+ * Definition for binary tree with next pointer.
8
+ * function TreeLinkNode(val) {
9
+ * this.val = val;
10
+ * this.left = this.right = this.next = null;
11
+ * }
12
+ */
13
+
14
+ /**
15
+ * @param {TreeLinkNode } root
16
+ * @return {void } Do not return anything, modify tree in-place instead.
17
+ */
18
+ var connect = function ( root ) {
19
+ if ( ! root )
20
+ return ;
21
+
22
+ // use BFS
23
+ var q = [ { node : root , step : 0 } ] ;
24
+
25
+ while ( q . length ) {
26
+ var item = q . shift ( ) ;
27
+ var node = item . node ;
28
+ var step = item . step ;
29
+
30
+ node . left && q . push ( { node : node . left , step : step + 1 } ) ;
31
+ node . right && q . push ( { node : node . right , step : step + 1 } ) ;
32
+
33
+ q . length && ( step === q [ 0 ] . step ) && ( node . next = q [ 0 ] . node ) ;
34
+ }
35
+ } ;
Original file line number Diff line number Diff line change
1
+ // Source : https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
2
+ // Author : Han Zichi
3
+ // Date : 2016-08-29
4
+ // Note : You may only use constant extra space
5
+
6
+ /**
7
+ * Definition for binary tree with next pointer.
8
+ * function TreeLinkNode(val) {
9
+ * this.val = val;
10
+ * this.left = this.right = this.next = null;
11
+ * }
12
+ */
13
+
14
+ /**
15
+ * @param {TreeLinkNode } root
16
+ * @return {void } Do not return anything, modify tree in-place instead.
17
+ */
18
+ var connect = function ( root ) {
19
+ if ( ! root )
20
+ return ;
21
+
22
+ if ( root . left ) {
23
+ root . left . next = root . right ;
24
+
25
+ if ( root . next )
26
+ root . right . next = root . next . left ;
27
+ }
28
+
29
+ connect ( root . left ) ;
30
+ connect ( root . right ) ;
31
+ } ;
You can’t perform that action at this time.
0 commit comments