-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0235_lowest_common_ancestor_of_bst.html
More file actions
485 lines (417 loc) · 16.6 KB
/
Copy path0235_lowest_common_ancestor_of_bst.html
File metadata and controls
485 lines (417 loc) · 16.6 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>235 - Lowest Common Ancestor of BST</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">#235</span> Lowest Common Ancestor of BST</h1>
<p>
Find the lowest common ancestor (LCA) of two nodes in a BST.
Use BST property: if both nodes are smaller, go left; if both larger, go right; else current is LCA.
</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/0235_lowest_common_ancestor_of_a_binary_search_tree/0235_lowest_common_ancestor_of_a_binary_search_tree.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>
<section class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="controls">
<button id="autoRunBtn" class="btn">▶ Auto Run</button>
<button id="stepBtn" class="btn btn-success">Step</button>
<button id="resetBtn" class="btn btn-danger">Reset</button>
<select id="pSelect" class="btn" style="background: #f8fafc; color: #1e293b;">
<option value="2">p = 2</option>
<option value="0">p = 0</option>
<option value="4">p = 4</option>
<option value="8">p = 8</option>
</select>
<select id="qSelect" class="btn" style="background: #f8fafc; color: #1e293b;">
<option value="8">q = 8</option>
<option value="4">q = 4</option>
<option value="7">q = 7</option>
<option value="9">q = 9</option>
</select>
</div>
<div class="status" id="status">Click Auto Run to find LCA of p and q</div>
<svg id="visualization"></svg>
</section>
<section class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import Optional
"""
LeetCode 235: Lowest Common Ancestor of a Binary Search Tree
Problem from LeetCode: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes p and q
as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)."
Example 1:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.
Example 2:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
Example 3:
Input: root = [2,1], p = 2, q = 1
Output: 2
Constraints:
- The number of nodes in the tree is in the range [2, 10^5].
- -10^9 <= Node.val <= 10^9
- All Node.val are unique.
- p != q
- p and q will exist in the BST.
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowest_common_ancestor(self, root: 'TreeNode', p: 'TreeNode', q:
'TreeNode') ->'TreeNode':
"""
Find the lowest common ancestor (LCA) node of two given nodes in a binary search tree.
The lowest common ancestor is defined between two nodes p and q as the lowest node in T
that has both p and q as descendants (where we allow a node to be a descendant of itself).
Args:
root: Root node of the BST
p: First node
q: Second node
Returns:
TreeNode: The LCA node
"""
parent_val = root.val
p_val = p.val
q_val = q.val
if p_val > parent_val and q_val > parent_val:
return self.lowest_common_ancestor(root.right, p, q)
elif p_val < parent_val and q_val < parent_val:
return self.lowest_common_ancestor(root.left, p, q)
else:
return root
def lowest_common_ancestor_iterative(self, root: 'TreeNode', p:
'TreeNode', q: 'TreeNode') ->'TreeNode':
"""
Find the lowest common ancestor using an iterative approach.
Args:
root: Root node of the BST
p: First node
q: Second node
Returns:
TreeNode: The LCA node
"""
current = root
p_val = p.val
q_val = q.val
while current:
parent_val = current.val
if p_val > parent_val and q_val > parent_val:
current = current.right
elif p_val < parent_val and q_val < parent_val:
current = current.left
else:
return current
return None
if __name__ == '__main__':
# Example usage based on LeetCode sample
# Creating the BST from Example 1: [6,2,8,0,4,7,9,null,null,3,5]
root = TreeNode(6)
root.left = TreeNode(2)
root.right = TreeNode(8)
root.left.left = TreeNode(0)
root.left.right = TreeNode(4)
root.right.left = TreeNode(7)
root.right.right = TreeNode(9)
root.left.right.left = TreeNode(3)
root.left.right.right = TreeNode(5)
solution = Solution()
# Example 1: p = 2, q = 8
p = root.left # Node with value 2
q = root.right # Node with value 8
result = solution.lowest_common_ancestor(root, p, q)
print(f"LCA of {p.val} and {q.val} is: {result.val}") # Output: 6
# Example 2: p = 2, q = 4
p = root.left # Node with value 2
q = root.left.right # Node with value 4
result = solution.lowest_common_ancestor(root, p, q)
print(f"LCA of {p.val} and {q.val} is: {result.val}") # Output: 2
</pre>
</div>
</section>
</div>
<script>
const width = 900;
const height = 550;
const svg = d3.select("#visualization")
.attr("width", width)
.attr("height", height);
// BST: [6,2,8,0,4,7,9,null,null,3,5]
const tree = {
val: 6,
left: {
val: 2,
left: { val: 0, left: null, right: null },
right: {
val: 4,
left: { val: 3, left: null, right: null },
right: { val: 5, left: null, right: null }
}
},
right: {
val: 8,
left: { val: 7, left: null, right: null },
right: { val: 9, left: null, right: null }
}
};
let pVal = 2;
let qVal = 8;
let currentNode = null;
let lca = null;
let pathNodes = [];
let animationTimer = null;
function reset() {
pVal = parseInt(document.getElementById("pSelect").value);
qVal = parseInt(document.getElementById("qSelect").value);
currentNode = tree;
lca = null;
pathNodes = [tree.val];
if (animationTimer) clearInterval(animationTimer);
document.getElementById("status").textContent =
`Finding LCA of p=${pVal} and q=${qVal}`;
render();
}
function render() {
svg.selectAll("*").remove();
// Draw tree
drawTree(tree, 450, 100, 0);
// Draw legend
drawLegend();
// Draw explanation
drawExplanation();
}
function drawTree(node, x, y, level) {
if (!node) return;
const spacing = 150 / (level + 1);
// Draw edges
if (node.left) {
svg.append("line")
.attr("x1", x)
.attr("y1", y)
.attr("x2", x - spacing)
.attr("y2", y + 70)
.attr("stroke", "#94a3b8")
.attr("stroke-width", 2);
drawTree(node.left, x - spacing, y + 70, level + 1);
}
if (node.right) {
svg.append("line")
.attr("x1", x)
.attr("y1", y)
.attr("x2", x + spacing)
.attr("y2", y + 70)
.attr("stroke", "#94a3b8")
.attr("stroke-width", 2);
drawTree(node.right, x + spacing, y + 70, level + 1);
}
// Determine node color
const isP = node.val === pVal;
const isQ = node.val === qVal;
const isLCA = lca && node.val === lca.val;
const isCurrent = currentNode && node.val === currentNode.val && !lca;
const isOnPath = pathNodes.includes(node.val);
let fill = "#f8fafc";
let stroke = "#94a3b8";
if (isLCA) {
fill = "#d1fae5";
stroke = "#10b981";
} else if (isP || isQ) {
fill = "#fce7f3";
stroke = "#ec4899";
} else if (isCurrent) {
fill = "#fef3c7";
stroke = "#f59e0b";
} else if (isOnPath) {
fill = "#dbeafe";
stroke = "#3b82f6";
}
// Draw node
svg.append("circle")
.attr("cx", x)
.attr("cy", y)
.attr("r", 25)
.attr("fill", fill)
.attr("stroke", stroke)
.attr("stroke-width", isLCA || isCurrent ? 4 : 2);
svg.append("text")
.attr("x", x)
.attr("y", y + 6)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text(node.val);
// Labels for p and q
if (isP || isQ) {
svg.append("text")
.attr("x", x)
.attr("y", y - 32)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold")
.attr("fill", "#ec4899")
.text(isP && isQ ? "p, q" : (isP ? "p" : "q"));
}
// LCA label
if (isLCA) {
svg.append("text")
.attr("x", x)
.attr("y", y - 32)
.attr("text-anchor", "middle")
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#10b981")
.text("LCA");
}
}
function drawLegend() {
const x = 50;
const y = 80;
const items = [
{ color: "#fce7f3", stroke: "#ec4899", label: "Target nodes (p, q)" },
{ color: "#fef3c7", stroke: "#f59e0b", label: "Current node" },
{ color: "#dbeafe", stroke: "#3b82f6", label: "Visited path" },
{ color: "#d1fae5", stroke: "#10b981", label: "LCA found" }
];
svg.append("text")
.attr("x", x)
.attr("y", y - 20)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("Legend:");
items.forEach((item, i) => {
svg.append("circle")
.attr("cx", x + 10)
.attr("cy", y + i * 25)
.attr("r", 8)
.attr("fill", item.color)
.attr("stroke", item.stroke);
svg.append("text")
.attr("x", x + 25)
.attr("y", y + i * 25 + 5)
.attr("font-size", "11px")
.attr("fill", "#1e293b")
.text(item.label);
});
}
function drawExplanation() {
const y = 430;
svg.append("text")
.attr("x", 50)
.attr("y", y)
.attr("font-size", "14px")
.attr("font-weight", "bold")
.attr("fill", "#1e293b")
.text("BST Property for LCA:");
svg.append("text")
.attr("x", 50)
.attr("y", y + 25)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("• If both p and q are greater than current → go RIGHT");
svg.append("text")
.attr("x", 50)
.attr("y", y + 45)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("• If both p and q are smaller than current → go LEFT");
svg.append("text")
.attr("x", 50)
.attr("y", y + 65)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("• Otherwise (split point) → current is the LCA");
svg.append("text")
.attr("x", 50)
.attr("y", y + 90)
.attr("font-size", "12px")
.attr("fill", "#64748b")
.text("Time: O(h) where h is tree height | Space: O(1) iterative");
}
function step() {
if (lca) {
document.getElementById("status").textContent =
`✓ LCA of ${pVal} and ${qVal} is ${lca.val}`;
return;
}
if (!currentNode) {
document.getElementById("status").textContent = "Node not found!";
return;
}
const currVal = currentNode.val;
if (pVal > currVal && qVal > currVal) {
document.getElementById("status").textContent =
`Both ${pVal} and ${qVal} > ${currVal}. Go RIGHT.`;
currentNode = currentNode.right;
if (currentNode) pathNodes.push(currentNode.val);
} else if (pVal < currVal && qVal < currVal) {
document.getElementById("status").textContent =
`Both ${pVal} and ${qVal} < ${currVal}. Go LEFT.`;
currentNode = currentNode.left;
if (currentNode) pathNodes.push(currentNode.val);
} else {
lca = currentNode;
document.getElementById("status").textContent =
`✓ Split point! LCA of ${pVal} and ${qVal} is ${lca.val}`;
}
render();
}
function autoRun() {
if (animationTimer) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
document.getElementById("autoRunBtn").textContent = "⏸ Pause";
animationTimer = setInterval(() => {
if (lca) {
clearInterval(animationTimer);
animationTimer = null;
document.getElementById("autoRunBtn").textContent = "▶ Auto Run";
return;
}
step();
}, 1000);
}
document.getElementById("autoRunBtn").addEventListener("click", autoRun);
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("resetBtn").addEventListener("click", reset);
document.getElementById("pSelect").addEventListener("change", reset);
document.getElementById("qSelect").addEventListener("change", reset);
reset();
</script>
</body>
</html>