-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0199_binary_tree_right_side_view.html
More file actions
597 lines (513 loc) · 20.7 KB
/
0199_binary_tree_right_side_view.html
File metadata and controls
597 lines (513 loc) · 20.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Binary Tree Right Side View - Algorithm Visualization</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
</div>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#0199</span> Binary Tree Right Side View</h1>
<p>
Given the root of a binary tree, imagine yourself standing on the <strong>right side</strong> of it.
Return the values of the nodes you can see ordered from top to bottom.
</p>
<p><strong>Example:</strong> [1,2,3,null,5,null,4] → [1,3,4]</p>
<p><strong>Approach:</strong> BFS level order, take the rightmost node at each level</p>
<p><strong>Time Complexity:</strong> O(n) | <strong>Space Complexity:</strong> O(n)</p>
<div class="problem-meta">
<span class="meta-tag">🌳 Tree</span>
<span class="meta-tag">⏱️ O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0199_binary_tree_right_side_view/0199_binary_tree_right_side_view.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Tree traversal is like <strong>exploring a family tree</strong>:</p>
<ul>
<li><strong>Root:</strong> Start at the top node</li>
<li><strong>Recurse:</strong> Visit left and right children</li>
<li><strong>Base case:</strong> Stop at null/leaf nodes</li>
<li><strong>Combine:</strong> Build answer from subtree results</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="stepBtn" class="btn">Step</button>
<button id="autoBtn" class="btn">Auto Run</button>
<button id="resetBtn" class="btn btn-secondary">Reset</button>
<div class="speed-control">
<label for="speedSlider">Speed:</label>
<input type="range" id="speedSlider" min="1" max="10" value="5">
</div>
</div>
<svg id="visualization" width="900" height="500"></svg>
<div class="variables-display">
<div id="varDisplay"></div>
</div>
<div class="status-message" id="statusMessage">Press "Step" or "Auto Run" to begin</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from collections import deque
from typing import List, Optional
"""
LeetCode Binary Tree Right Side View
Problem from LeetCode: https://leetcode.com/problems/binary-tree-right-side-view/
Description:
Given the root of a binary tree, imagine yourself standing on the right side of it,
return the values of the nodes you can see ordered from top to bottom.
Example 1:
Input: root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Explanation: The right side view of the tree is [1,3,4].
Example 2:
Input: root = [1,null,3]
Output: [1,3]
Example 3:
Input: root = []
Output: []
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def right_side_view(self, root: Optional[TreeNode]) -> List[int]:
"""
Returns the values of nodes visible from the right side of the binary tree.
Uses a level-order traversal (BFS) approach.
Args:
root: Root of the binary tree
Returns:
List[int]: Values of nodes visible from the right side
"""
result = []
if not root:
return result
queue = deque([root])
while queue:
level_size = len(queue)
for i in range(level_size):
current_node = queue.popleft()
if i == level_size - 1:
result.append(current_node.val)
if current_node.left:
queue.append(current_node.left)
if current_node.right:
queue.append(current_node.right)
return result
def right_side_view_dfs(self, root: Optional[TreeNode]) -> List[int]:
"""
Alternative implementation using DFS approach.
Args:
root: Root of the binary tree
Returns:
List[int]: Values of nodes visible from the right side
"""
result = []
def dfs(node, level):
if not node:
return
# If this is the first node we've seen at this level
if len(result) == level:
result.append(node.val)
# Visit right first, then left (to get rightmost nodes first)
dfs(node.right, level + 1)
dfs(node.left, level + 1)
dfs(root, 0)
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1: [1,2,3,null,5,null,4]
root1 = TreeNode(1)
root1.left = TreeNode(2)
root1.right = TreeNode(3)
root1.left.right = TreeNode(5)
root1.right.right = TreeNode(4)
result1 = solution.right_side_view(root1)
print(f"Example 1: {result1}") # Expected output: [1, 3, 4]
# Example 2: [1,null,3]
root2 = TreeNode(1)
root2.right = TreeNode(3)
result2 = solution.right_side_view(root2)
print(f"Example 2: {result2}") # Expected output: [1, 3]
# Example 3: []
result3 = solution.right_side_view(None)
print(f"Example 3: {result3}") # Expected output: []
# Compare with DFS approach
print("\nUsing DFS approach:")
print(f"Example 1: {solution.right_side_view_dfs(root1)}") # Expected output: [1, 3, 4]
print(f"Example 2: {solution.right_side_view_dfs(root2)}") # Expected output: [1, 3]
</pre>
</div>
</div>
</div>
<script>
// Tree: [1,2,3,null,5,null,4]
// 1
// / \
// 2 3
// \ \
// 5 4
const positions = {
1: { x: 250, y: 80 },
2: { x: 150, y: 160 },
3: { x: 350, y: 160 },
5: { x: 200, y: 240 },
4: { x: 400, y: 240 }
};
const edges = [[1, 2], [1, 3], [2, 5], [3, 4]];
// State
let step = 0;
let autoRunning = false;
let autoInterval = null;
// Generate steps
const steps = [];
function generateSteps() {
steps.length = 0;
steps.push({
type: 'init',
queue: [1],
processed: [],
visible: [],
level: 0,
message: 'Initialize: Standing on the right side, looking at the tree'
});
// Level 0
steps.push({
type: 'level_start',
queue: [1],
processed: [],
visible: [],
level: 0,
levelSize: 1,
message: 'Level 0: Only 1 node. It must be visible from the right.'
});
steps.push({
type: 'process',
queue: [2, 3],
processed: [1],
visible: [1],
level: 0,
currentNode: 1,
isLast: true,
message: 'Node 1 is the last (rightmost) in level 0. Add to result!'
});
// Level 1
steps.push({
type: 'level_start',
queue: [2, 3],
processed: [1],
visible: [1],
level: 1,
levelSize: 2,
message: 'Level 1: 2 nodes (2, 3). Only rightmost (3) is visible.'
});
steps.push({
type: 'process',
queue: [3, 5],
processed: [1, 2],
visible: [1],
level: 1,
currentNode: 2,
isLast: false,
message: 'Node 2 is NOT the last in level. Skip (blocked by node 3).'
});
steps.push({
type: 'process',
queue: [5, 4],
processed: [1, 2, 3],
visible: [1, 3],
level: 1,
currentNode: 3,
isLast: true,
message: 'Node 3 is the last (rightmost) in level 1. Add to result!'
});
// Level 2
steps.push({
type: 'level_start',
queue: [5, 4],
processed: [1, 2, 3],
visible: [1, 3],
level: 2,
levelSize: 2,
message: 'Level 2: 2 nodes (5, 4). Only rightmost (4) is visible.'
});
steps.push({
type: 'process',
queue: [4],
processed: [1, 2, 3, 5],
visible: [1, 3],
level: 2,
currentNode: 5,
isLast: false,
message: 'Node 5 is NOT the last in level. Skip (blocked by node 4).'
});
steps.push({
type: 'process',
queue: [],
processed: [1, 2, 3, 5, 4],
visible: [1, 3, 4],
level: 2,
currentNode: 4,
isLast: true,
message: 'Node 4 is the last (rightmost) in level 2. Add to result!'
});
steps.push({
type: 'done',
queue: [],
processed: [1, 2, 3, 5, 4],
visible: [1, 3, 4],
message: 'Done! Right side view: [1, 3, 4]'
});
}
// SVG setup
const svg = d3.select("#visualization");
const width = 900;
const height = 500;
function draw(currentStep) {
svg.selectAll("*").remove();
const data = currentStep || steps[0];
// Draw viewing perspective
svg.append("text")
.attr("x", 550)
.attr("y", 160)
.attr("text-anchor", "middle")
.attr("fill", "#667eea")
.attr("font-size", "24px")
.text("👁️");
svg.append("text")
.attr("x", 550)
.attr("y", 185)
.attr("text-anchor", "middle")
.attr("fill", "#667eea")
.text("You are here");
// Draw viewing lines
if (data.type !== 'init') {
[80, 160, 240].forEach((y, i) => {
const visibleNode = data.visible && data.visible[i];
if (visibleNode !== undefined) {
const pos = positions[visibleNode];
if (pos) {
svg.append("line")
.attr("x1", 530)
.attr("y1", 150)
.attr("x2", pos.x + 25)
.attr("y2", pos.y)
.attr("stroke", "#4ade80")
.attr("stroke-width", 2)
.attr("stroke-dasharray", "5,5")
.attr("opacity", 0.7);
}
}
});
}
// Draw tree label
svg.append("text")
.attr("x", 250)
.attr("y", 30)
.attr("text-anchor", "middle")
.attr("class", "label")
.text("Binary Tree");
// Draw edges
edges.forEach(([from, to]) => {
svg.append("line")
.attr("x1", positions[from].x)
.attr("y1", positions[from].y + 20)
.attr("x2", positions[to].x)
.attr("y2", positions[to].y - 20)
.attr("stroke", "#d1d5db")
.attr("stroke-width", 2);
});
// Draw level lines
[0, 1, 2].forEach(level => {
const y = 80 + level * 80;
svg.append("line")
.attr("x1", 50)
.attr("y1", y)
.attr("x2", 480)
.attr("y2", y)
.attr("stroke", data.level === level ? "#f59e0b" : "#e5e7eb")
.attr("stroke-width", data.level === level ? 2 : 1)
.attr("stroke-dasharray", "3,3");
svg.append("text")
.attr("x", 30)
.attr("y", y + 5)
.attr("fill", data.level === level ? "#f59e0b" : "#9ca3af")
.attr("font-size", "12px")
.text(`L${level}`);
});
// Draw nodes
[1, 2, 3, 5, 4].forEach(val => {
const pos = positions[val];
let fill = "#667eea";
let stroke = "none";
let strokeWidth = 0;
if (data.currentNode === val) {
fill = data.isLast ? "#4ade80" : "#f59e0b";
stroke = data.isLast ? "#16a34a" : "#d97706";
strokeWidth = 3;
} else if (data.visible && data.visible.includes(val)) {
fill = "#4ade80";
} else if (data.processed && data.processed.includes(val)) {
fill = "#9ca3af";
} else if (data.queue && data.queue.includes(val)) {
fill = "#06b6d4";
}
svg.append("circle")
.attr("cx", pos.x)
.attr("cy", pos.y)
.attr("r", 22)
.attr("fill", fill)
.attr("stroke", stroke)
.attr("stroke-width", strokeWidth);
svg.append("text")
.attr("x", pos.x)
.attr("y", pos.y + 6)
.attr("text-anchor", "middle")
.attr("fill", "white")
.attr("font-weight", "bold")
.attr("font-size", "16px")
.text(val);
});
// Draw result (right side view)
svg.append("text")
.attr("x", 650)
.attr("y", 60)
.attr("class", "label")
.text("Right Side View:");
if (data.visible && data.visible.length > 0) {
data.visible.forEach((val, i) => {
const isNew = data.currentNode === val && data.isLast;
svg.append("rect")
.attr("x", 650 + i * 55)
.attr("y", 70)
.attr("width", 45)
.attr("height", 40)
.attr("rx", 8)
.attr("fill", "#4ade80")
.attr("stroke", isNew ? "#16a34a" : "none")
.attr("stroke-width", isNew ? 3 : 0);
svg.append("text")
.attr("x", 672 + i * 55)
.attr("y", 97)
.attr("text-anchor", "middle")
.attr("fill", "white")
.attr("font-weight", "bold")
.attr("font-size", "18px")
.text(val);
});
} else {
svg.append("text")
.attr("x", 650)
.attr("y", 95)
.attr("fill", "#9ca3af")
.text("[]");
}
// Draw queue
svg.append("text")
.attr("x", 650)
.attr("y", 170)
.attr("class", "label")
.text("Queue:");
if (data.queue && data.queue.length > 0) {
data.queue.forEach((val, i) => {
svg.append("rect")
.attr("x", 650 + i * 45)
.attr("y", 180)
.attr("width", 35)
.attr("height", 30)
.attr("rx", 6)
.attr("fill", "#06b6d4");
svg.append("text")
.attr("x", 667 + i * 45)
.attr("y", 200)
.attr("text-anchor", "middle")
.attr("fill", "white")
.attr("font-weight", "bold")
.text(val);
});
} else {
svg.append("text")
.attr("x", 650)
.attr("y", 200)
.attr("fill", "#9ca3af")
.text("(empty)");
}
// Legend
const legendY = 400;
svg.append("circle").attr("cx", 100).attr("cy", legendY).attr("r", 10).attr("fill", "#4ade80");
svg.append("text").attr("x", 115).attr("y", legendY + 4).attr("fill", "#4b5563").text("Visible");
svg.append("circle").attr("cx", 210).attr("cy", legendY).attr("r", 10).attr("fill", "#9ca3af");
svg.append("text").attr("x", 225).attr("y", legendY + 4).attr("fill", "#4b5563").text("Blocked");
svg.append("circle").attr("cx", 320).attr("cy", legendY).attr("r", 10).attr("fill", "#06b6d4");
svg.append("text").attr("x", 335).attr("y", legendY + 4).attr("fill", "#4b5563").text("In Queue");
svg.append("circle").attr("cx", 430).attr("cy", legendY).attr("r", 10).attr("fill", "#f59e0b");
svg.append("text").attr("x", 445).attr("y", legendY + 4).attr("fill", "#4b5563").text("Processing");
// Update status
document.getElementById("statusMessage").textContent = data.message;
// Update variables
document.getElementById("varDisplay").innerHTML = `
<span class="var-item">Level: ${data.level !== undefined ? data.level : 'N/A'}</span>
<span class="var-item">Queue: [${data.queue ? data.queue.join(', ') : ''}]</span>
<span class="var-item">Result: [${data.visible ? data.visible.join(', ') : ''}]</span>
`;
}
function doStep() {
if (step >= steps.length) {
stopAuto();
return;
}
draw(steps[step]);
step++;
}
function stopAuto() {
autoRunning = false;
if (autoInterval) {
clearInterval(autoInterval);
autoInterval = null;
}
document.getElementById("autoBtn").textContent = "Auto Run";
}
function toggleAuto() {
if (autoRunning) {
stopAuto();
} else {
autoRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
const speed = 11 - document.getElementById("speedSlider").value;
autoInterval = setInterval(() => {
if (step >= steps.length) {
stopAuto();
return;
}
doStep();
}, speed * 200);
}
}
function reset() {
stopAuto();
step = 0;
draw(steps[0]);
}
// Initialize
generateSteps();
draw(steps[0]);
// Event listeners
document.getElementById("stepBtn").addEventListener("click", doStep);
document.getElementById("autoBtn").addEventListener("click", toggleAuto);
document.getElementById("resetBtn").addEventListener("click", reset);
</script>
</body>
</html>