Skip to content

Commit 3b30116

Browse files
committed
Add solution for populating next right pointers in each node ii
1 parent 15dd5ff commit 3b30116

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Populating Next Right Pointers in Each Node II.js

+52
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,55 @@ var connect = function(root) {
6565
nextRow = [];
6666
}
6767
};
68+
69+
70+
// O(1) space solution
71+
72+
/**
73+
* Definition for binary tree with next pointer.
74+
* function TreeLinkNode(val) {
75+
* this.val = val;
76+
* this.left = this.right = this.next = null;
77+
* }
78+
*/
79+
80+
/**
81+
* @param {TreeLinkNode} root
82+
* @return {void} Do not return anything, modify tree in-place instead.
83+
*/
84+
var connect = function(root) {
85+
let nextHead = null;
86+
let cur = root;
87+
let nextCur = null;
88+
89+
while (cur !== null) {
90+
91+
while (cur !== null) {
92+
if (cur.left) {
93+
if (!nextHead) {
94+
nextHead = cur.left;
95+
nextCur = nextHead;
96+
} else {
97+
nextCur.next = cur.left;
98+
nextCur = nextCur.next;
99+
}
100+
}
101+
102+
if (cur.right) {
103+
if (!nextHead) {
104+
nextHead = cur.right;
105+
nextCur = nextHead;
106+
} else {
107+
nextCur.next = cur.right;
108+
nextCur = nextCur.next;
109+
}
110+
}
111+
112+
cur = cur.next;
113+
}
114+
115+
cur = nextHead;
116+
nextHead = null;
117+
nextCur = null;
118+
}
119+
};

0 commit comments

Comments
 (0)