Skip to content

Commit 9055b4a

Browse files
authored
feat: update ts solution to lc problem: No.199 (doocs#2821)
1 parent 7dff3e5 commit 9055b4a

File tree

3 files changed

+39
-27
lines changed

3 files changed

+39
-27
lines changed

solution/0100-0199/0199.Binary Tree Right Side View/README.md

+13-9
Original file line numberDiff line numberDiff line change
@@ -213,19 +213,23 @@ func rightSideView(root *TreeNode) (ans []int) {
213213
*/
214214

215215
function rightSideView(root: TreeNode | null): number[] {
216-
const ans = [];
217216
if (!root) {
218-
return ans;
217+
return [];
219218
}
220-
const q = [root];
219+
let q = [root];
220+
const ans: number[] = [];
221221
while (q.length) {
222-
const n = q.length;
223-
ans.push(q[n - 1].val);
224-
for (let i = 0; i < n; ++i) {
225-
const { left, right } = q.shift();
226-
left && q.push(left);
227-
right && q.push(right);
222+
const nextq: TreeNode[] = [];
223+
ans.push(q.at(-1)!.val);
224+
for (const { left, right } of q) {
225+
if (left) {
226+
nextq.push(left);
227+
}
228+
if (right) {
229+
nextq.push(right);
230+
}
228231
}
232+
q = nextq;
229233
}
230234
return ans;
231235
}

solution/0100-0199/0199.Binary Tree Right Side View/README_EN.md

+13-9
Original file line numberDiff line numberDiff line change
@@ -203,19 +203,23 @@ func rightSideView(root *TreeNode) (ans []int) {
203203
*/
204204

205205
function rightSideView(root: TreeNode | null): number[] {
206-
const ans = [];
207206
if (!root) {
208-
return ans;
207+
return [];
209208
}
210-
const q = [root];
209+
let q = [root];
210+
const ans: number[] = [];
211211
while (q.length) {
212-
const n = q.length;
213-
ans.push(q[n - 1].val);
214-
for (let i = 0; i < n; ++i) {
215-
const { left, right } = q.shift();
216-
left && q.push(left);
217-
right && q.push(right);
212+
const nextq: TreeNode[] = [];
213+
ans.push(q.at(-1)!.val);
214+
for (const { left, right } of q) {
215+
if (left) {
216+
nextq.push(left);
217+
}
218+
if (right) {
219+
nextq.push(right);
220+
}
218221
}
222+
q = nextq;
219223
}
220224
return ans;
221225
}

solution/0100-0199/0199.Binary Tree Right Side View/Solution.ts

+13-9
Original file line numberDiff line numberDiff line change
@@ -13,19 +13,23 @@
1313
*/
1414

1515
function rightSideView(root: TreeNode | null): number[] {
16-
const ans = [];
1716
if (!root) {
18-
return ans;
17+
return [];
1918
}
20-
const q = [root];
19+
let q = [root];
20+
const ans: number[] = [];
2121
while (q.length) {
22-
const n = q.length;
23-
ans.push(q[n - 1].val);
24-
for (let i = 0; i < n; ++i) {
25-
const { left, right } = q.shift();
26-
left && q.push(left);
27-
right && q.push(right);
22+
const nextq: TreeNode[] = [];
23+
ans.push(q.at(-1)!.val);
24+
for (const { left, right } of q) {
25+
if (left) {
26+
nextq.push(left);
27+
}
28+
if (right) {
29+
nextq.push(right);
30+
}
2831
}
32+
q = nextq;
2933
}
3034
return ans;
3135
}

0 commit comments

Comments
 (0)