-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0366_find_leaves_of_binary_tree.html
More file actions
441 lines (371 loc) · 15.5 KB
/
0366_find_leaves_of_binary_tree.html
File metadata and controls
441 lines (371 loc) · 15.5 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LC 366: Find Leaves of Binary Tree - Algorithm Visualization</title>
<link rel="stylesheet" href="styles.css">
<script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
<div class="container">
<div class="problem-info">
<h1><span class="problem-number">#366</span> Find Leaves of Binary Tree</h1>
<p>Collect and remove leaves repeatedly until tree is empty. Return leaves at each step grouped together.</p>
<div class="problem-meta">
<span class="meta-tag">🌳 Tree</span>
<span class="meta-tag">🔄 DFS</span>
<span class="meta-tag">⏱️ O(n)</span>
<span class="meta-tag">💾 O(n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0366_find_leaves_of_binary_tree/0366_find_leaves_of_binary_tree.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Calculate <strong>height from bottom</strong> for each node:</p>
<ul>
<li><strong>Leaf nodes:</strong> Height = 0 (collected first)</li>
<li><strong>Internal nodes:</strong> Height = 1 + max(left, right)</li>
<li><strong>Group by height:</strong> Same height = same collection round</li>
<li><strong>Result:</strong> Nodes grouped by their "distance from leaves"</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button class="btn btn-primary" id="startBtn" onclick="start()">▶ Start</button>
<button class="btn" onclick="stepForward()">Step →</button>
<button class="btn btn-warning" onclick="reset()">Reset</button>
</div>
<div class="status-message" id="statusMessage">
Click Start to collect leaves layer by layer
</div>
<div style="display: flex; gap: 30px; flex-wrap: wrap; margin-top: 20px;">
<div style="flex: 2; min-width: 350px;">
<svg id="treeViz" width="100%" height="320"></svg>
</div>
<div style="flex: 1; min-width: 200px;">
<h4>🍂 Collected Leaves</h4>
<div id="collectedDisplay" style="padding: 15px; background: #fff3e0; border-radius: 12px; min-height: 150px;"></div>
<h4 style="margin-top: 15px;">🔢 Current Round</h4>
<div id="roundDisplay" style="padding: 20px; background: #e3f2fd; border-radius: 12px; text-align: center; font-size: 2em; font-weight: bold; color: #2196f3;">
0
</div>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import List, Optional
"""
LeetCode Find Leaves of Binary Tree
Problem from LeetCode: https://leetcode.com/problems/find-leaves-of-binary-tree/
Description:
Given the root of a binary tree, collect a tree's nodes as if you were doing this:
1. Collect all the leaf nodes.
2. Remove all the leaf nodes.
3. Repeat until the tree is empty.
Example 1:
Input: root = [1,2,3,4,5]
1
/ \
2 3
/ \
4 5
Output: [[4,5,3],[2],[1]]
Explanation:
[[4,5,3]] represents the leaves in the first round.
[[2]] represents the leaves in the second round.
[[1]] represents the leaves in the third round.
Example 2:
Input: root = [1]
Output: [[1]]
Constraints:
The number of nodes in the tree is in the range [1, 100].
-100 <= Node.val <= 100
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def find_leaves(self, root: Optional[TreeNode]) ->List[List[int]]:
"""
Find and remove all leaf nodes from a binary tree until the tree is empty.
Args:
root: Root of the binary tree
Returns:
List[List[int]]: List of leaves at each level, from leaves to root
"""
result = []
while root:
leaves = []
root = self.removeLeaves(root, leaves)
result.append(leaves)
return result
def removeLeaves(self, node: Optional[TreeNode], leaves: List[int]
) ->Optional[TreeNode]:
"""
Remove leaf nodes and collect their values.
Args:
node: Current node in the tree
leaves: List to collect leaf node values
Returns:
TreeNode: The new tree after removing leaves, or None if tree becomes empty
"""
if not node:
return None
if not node.left and not node.right:
leaves.append(node.val)
return None
node.left = self.removeLeaves(node.left, leaves)
node.right = self.removeLeaves(node.right, leaves)
return node
def find_leaves_by_height(self, root: Optional[TreeNode]) ->List[List[int]
]:
"""
Alternative implementation that groups nodes by their height from bottom.
Args:
root: Root of the binary tree
Returns:
List[List[int]]: List of nodes grouped by their height from bottom
"""
result = []
def getHeight(node):
if not node:
return -1
left_height = getHeight(node.left)
right_height = getHeight(node.right)
height = 1 + max(left_height, right_height)
if len(result) <= height:
result.append([])
result[height].append(node.val)
return height
getHeight(root)
return result
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Create example tree for Example 1:
# 1
# / \
# 2 3
# / \
#4 5
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
# Using the iterative approach
result1 = solution.find_leaves(root)
print("Example 1 (iterative):")
print(result1) # Expected: [[4,5,3],[2],[1]]
# Recreate the tree for the alternative approach
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
# Using the height-based approach
result2 = solution.find_leaves_by_height(root)
print("Example 1 (height-based):")
print(result2) # Expected: [[4,5,3],[2],[1]]
</pre>
</div>
</div>
</div>
<script>
const tree = {
val: 1, id: 1, x: 250, y: 40, height: null,
left: {
val: 2, id: 2, x: 150, y: 120, height: null,
left: { val: 4, id: 4, x: 100, y: 200, height: null, left: null, right: null },
right: { val: 5, id: 5, x: 200, y: 200, height: null, left: null, right: null }
},
right: {
val: 3, id: 3, x: 350, y: 120, height: null,
left: null,
right: { val: 6, id: 6, x: 400, y: 200, height: null, left: null, right: null }
}
};
let collected = [];
let removedNodes = new Set();
let currentRound = -1;
let highlightedNodes = new Set();
let nodeHeights = {};
let isRunning = false;
let stepIndex = 0;
let steps = [];
function flattenTree(node, arr = []) {
if (!node) return arr;
arr.push(node);
flattenTree(node.left, arr);
flattenTree(node.right, arr);
return arr;
}
function computeHeights(node) {
if (!node) return -1;
const h = 1 + Math.max(computeHeights(node.left), computeHeights(node.right));
node.height = h;
nodeHeights[node.id] = h;
return h;
}
function precomputeSteps() {
steps = [];
computeHeights(tree);
const nodes = flattenTree(tree);
const maxHeight = Math.max(...Object.values(nodeHeights));
steps.push({
type: 'init',
collected: [],
removed: new Set(),
highlighted: new Set(),
round: -1,
message: 'Calculate height for each node (height = distance from leaves)'
});
for (let h = 0; h <= maxHeight; h++) {
const nodesAtHeight = nodes.filter(n => n.height === h);
const newCollected = [...(steps[steps.length - 1]?.collected || [])];
newCollected.push(nodesAtHeight.map(n => n.val));
const newRemoved = new Set(steps[steps.length - 1]?.removed || []);
nodesAtHeight.forEach(n => newRemoved.add(n.id));
steps.push({
type: 'collect',
collected: newCollected,
removed: newRemoved,
highlighted: new Set(nodesAtHeight.map(n => n.id)),
round: h,
message: `Round ${h}: Collect nodes with height ${h}: [${nodesAtHeight.map(n => n.val).join(', ')}]`
});
}
steps.push({
type: 'done',
collected: steps[steps.length - 1].collected,
removed: steps[steps.length - 1].removed,
highlighted: new Set(),
round: maxHeight,
message: `Done! Collected ${steps[steps.length - 1].collected.length} rounds of leaves.`
});
}
function render() {
const svg = d3.select("#treeViz");
svg.selectAll("*").remove();
const container = svg.node().parentElement;
const width = container.clientWidth;
const height = 320;
svg.attr("viewBox", `0 0 ${width} ${height}`);
const nodes = flattenTree(tree);
const g = svg.append("g").attr("transform", `translate(${(width - 500) / 2}, 0)`);
// Draw edges
function drawEdges(node) {
if (!node) return;
const removed = removedNodes.has(node.id);
if (removed) return;
if (node.left && !removedNodes.has(node.left.id)) {
g.append("line")
.attr("x1", node.x).attr("y1", node.y)
.attr("x2", node.left.x).attr("y2", node.left.y)
.attr("stroke", "#ccc").attr("stroke-width", 2);
}
if (node.right && !removedNodes.has(node.right.id)) {
g.append("line")
.attr("x1", node.x).attr("y1", node.y)
.attr("x2", node.right.x).attr("y2", node.right.y)
.attr("stroke", "#ccc").attr("stroke-width", 2);
}
drawEdges(node.left);
drawEdges(node.right);
}
drawEdges(tree);
// Draw nodes
nodes.forEach(node => {
const removed = removedNodes.has(node.id);
const highlighted = highlightedNodes.has(node.id);
if (removed && !highlighted) return;
let fill = '#667eea';
if (highlighted) fill = '#ff9800';
if (removed && highlighted) fill = '#f44336';
g.append("circle")
.attr("cx", node.x).attr("cy", node.y).attr("r", 25)
.attr("fill", fill)
.attr("stroke", highlighted ? '#e65100' : '#5a6fd6')
.attr("stroke-width", highlighted ? 4 : 2)
.attr("opacity", removed ? 0.5 : 1);
g.append("text")
.attr("x", node.x).attr("y", node.y + 6)
.attr("text-anchor", "middle")
.attr("fill", "white").attr("font-weight", "bold").attr("font-size", "16px")
.text(node.val);
// Height label
if (nodeHeights[node.id] !== undefined) {
g.append("text")
.attr("x", node.x + 30).attr("y", node.y - 15)
.attr("font-size", "11px")
.attr("fill", "#666")
.text(`h=${nodeHeights[node.id]}`);
}
});
// Update collected display
const collectedContainer = document.getElementById('collectedDisplay');
if (collected.length === 0) {
collectedContainer.innerHTML = '<span style="color: #999;">Leaves will be collected here...</span>';
} else {
collectedContainer.innerHTML = collected.map((round, i) =>
`<div style="margin: 8px 0; padding: 10px; background: ${i === currentRound ? '#ffeb3b' : '#fff'}; border-radius: 8px; border-left: 4px solid hsl(${i * 40}, 70%, 50%);">
<strong>Round ${i}:</strong> [${round.join(', ')}]
</div>`
).join('');
}
document.getElementById('roundDisplay').textContent = currentRound >= 0 ? currentRound : '-';
}
function stepForward() {
if (stepIndex >= steps.length) return;
const step = steps[stepIndex];
collected = step.collected;
removedNodes = step.removed;
highlightedNodes = step.highlighted;
currentRound = step.round;
document.getElementById('statusMessage').textContent = step.message;
if (step.type === 'done') {
isRunning = false;
document.getElementById('startBtn').textContent = '▶ Start';
}
stepIndex++;
render();
}
async function start() {
if (isRunning) {
isRunning = false;
document.getElementById('startBtn').textContent = '▶ Start';
return;
}
isRunning = true;
document.getElementById('startBtn').textContent = '⏸ Pause';
while (stepIndex < steps.length && isRunning) {
stepForward();
await new Promise(r => setTimeout(r, 1000));
}
}
function reset() {
isRunning = false;
stepIndex = 0;
collected = [];
removedNodes = new Set();
highlightedNodes = new Set();
currentRound = -1;
nodeHeights = {};
document.getElementById('statusMessage').textContent = 'Click Start to collect leaves layer by layer';
document.getElementById('startBtn').textContent = '▶ Start';
precomputeSteps();
render();
}
reset();
window.addEventListener('resize', render);
</script>
</body>
</html>