Skip to content

Commit 0f4d4b2

Browse files
committed
Add Populating Next Right Pointers in Each Node
1 parent 669729a commit 0f4d4b2

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
};
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
};

0 commit comments

Comments
 (0)