-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0098_validate_binary_search_tree.html
More file actions
535 lines (449 loc) · 19 KB
/
0098_validate_binary_search_tree.html
File metadata and controls
535 lines (449 loc) · 19 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Validate Binary Search Tree - LeetCode 98</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">#0098</span> Validate Binary Search Tree</h1>
<p><strong>Problem:</strong> Given a binary tree, determine if it is a valid BST (left subtree values < node < right subtree values).</p>
<p><strong>Pattern:</strong> DFS with Valid Range - Track min/max bounds for each node</p>
<div class="problem-meta">
<span class="meta-tag">🌳 Tree</span>
<span class="meta-tag">📚 Stack</span>
<span class="meta-tag">🔍 Binary Search</span>
<span class="meta-tag">⏱️ O(log n)</span>
</div>
<div class="file-ref">
📄 Python: <code>python/0098_validate_binary_search_tree/0098_validate_binary_search_tree.py</code>
</div>
</div>
<div class="explanation-panel">
<h4>🧠 How It Works (Layman's Terms)</h4>
<p>Binary search is like finding a word in a dictionary - <strong>eliminate half</strong> each time:</p>
<ul>
<li><strong>Check middle:</strong> Look at the middle element</li>
<li><strong>Compare:</strong> Is target less or greater?</li>
<li><strong>Eliminate:</strong> Discard half that can't contain the answer</li>
<li><strong>Repeat:</strong> Continue until found</li>
</ul>
</div>
<div class="visualization-section">
<h3>🎬 Step-by-Step Visualization</h3>
<div class="visualization">
<svg id="mainSvg"></svg>
</div>
<div class="controls">
<button id="stepBtn">Step</button>
<button id="autoBtn">Auto Run</button>
<button id="resetBtn">Reset</button>
<button id="toggleTreeBtn">Toggle: Valid Tree</button>
<div class="speed-control">
<label for="speed">Speed:</label>
<input type="range" id="speed" min="100" max="2000" value="800">
</div>
</div>
<div class="status" id="status">Click "Step" to validate the BST</div>
<div class="variables">
<div class="var-item">
<span class="var-label">Current Node:</span>
<span id="currentDisplay">-</span>
</div>
<div class="var-item">
<span class="var-label">Valid Range:</span>
<span id="rangeDisplay">(-∞, +∞)</span>
</div>
<div class="var-item">
<span class="var-label">Is Valid:</span>
<span id="validDisplay">-</span>
</div>
</div>
</div>
<div class="code-section">
<h3>💻 Python Solution</h3>
<div class="code-block">
<pre>from typing import Optional
"""
LeetCode Validate Binary Search Tree
Problem from LeetCode: https://leetcode.com/problems/validate-binary-search-tree/
Description:
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
Example 1:
Input: root = [2,1,3]
Output: true
Example 2:
Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def is_valid_bst(self, root: Optional[TreeNode]) -> bool:
"""
Determine if a binary tree is a valid binary search tree.
Args:
root: Root of the binary tree
Returns:
bool: True if the tree is a valid BST, False otherwise
"""
# Helper function for recursive validation with min/max boundaries
def validate(node, lower=float('-inf'), upper=float('inf')):
# Empty trees are valid BSTs
if not node:
return True
# Check if current node's value violates the BST property
if node.val <= lower or node.val >= upper:
return False
# Recursively check left and right subtrees
# Left subtree must have values less than the current node
# Right subtree must have values greater than the current node
return (validate(node.left, lower, node.val) and
validate(node.right, node.val, upper))
return validate(root)
def is_valid_bst_inorder(self, root: Optional[TreeNode]) -> bool:
"""
Validate BST using inorder traversal.
In a BST, inorder traversal should yield a sorted array.
Args:
root: Root of the binary tree
Returns:
bool: True if the tree is a valid BST, False otherwise
"""
prev = float('-inf')
# Helper function for inorder traversal
def inorder(node):
nonlocal prev
if not node:
return True
# Check left subtree
if not inorder(node.left):
return False
# Check current node's value against the previous value
if node.val <= prev:
return False
# Update previous value
prev = node.val
# Check right subtree
return inorder(node.right)
return inorder(root)
def is_valid_bst_iterative(self, root: Optional[TreeNode]) -> bool:
"""
Validate BST using iterative inorder traversal.
Args:
root: Root of the binary tree
Returns:
bool: True if the tree is a valid BST, False otherwise
"""
if not root:
return True
stack = []
prev = float('-inf')
current = root
while stack or current:
# Traverse to the leftmost node
while current:
stack.append(current)
current = current.left
# Check the current node
current = stack.pop()
# If current value is less than or equal to previous, it's not a BST
if current.val <= prev:
return False
# Update previous value
prev = current.val
# Move to the right subtree
current = current.right
return True
if __name__ == '__main__':
# Example usage based on LeetCode sample
solution = Solution()
# Example 1
# Tree:
# 2
# / \
# 1 3
root1 = TreeNode(2, TreeNode(1), TreeNode(3))
result1 = solution.is_valid_bst(root1)
print(f"Example 1: {result1}") # Expected output: True
# Example 2
# Tree:
# 5
# / \
# 1 4
# / \
# 3 6
root2 = TreeNode(5, TreeNode(1), TreeNode(4, TreeNode(3), TreeNode(6)))
result2 = solution.is_valid_bst(root2)
print(f"Example 2: {result2}") # Expected output: False
# Additional example
# Tree:
# 10
# / \
# 5 15
# / \
# 12 20
root3 = TreeNode(10, TreeNode(5), TreeNode(15, TreeNode(12), TreeNode(20)))
result3 = solution.is_valid_bst(root3)
print(f"Example 3: {result3}") # Expected output: True
# Compare with other implementations
print("\nUsing inorder traversal approach:")
print(f"Example 1: {solution.is_valid_bst_inorder(root1)}")
print(f"Example 2: {solution.is_valid_bst_inorder(root2)}")
print(f"Example 3: {solution.is_valid_bst_inorder(root3)}")
print("\nUsing iterative approach:")
print(f"Example 1: {solution.is_valid_bst_iterative(root1)}")
print(f"Example 2: {solution.is_valid_bst_iterative(root2)}")
print(f"Example 3: {solution.is_valid_bst_iterative(root3)}")
</pre>
</div>
</div>
</div>
<script>
// Valid BST
const validTree = {
val: 5,
left: {
val: 3,
left: {val: 1, left: null, right: null},
right: {val: 4, left: null, right: null}
},
right: {
val: 7,
left: {val: 6, left: null, right: null},
right: {val: 9, left: null, right: null}
}
};
// Invalid BST (4 should not be in right subtree of 5)
const invalidTree = {
val: 5,
left: {
val: 3,
left: {val: 1, left: null, right: null},
right: {val: 4, left: null, right: null}
},
right: {
val: 7,
left: {val: 4, left: null, right: null}, // Invalid! 4 < 5
right: {val: 9, left: null, right: null}
}
};
let useValidTree = true;
let tree = validTree;
let nodeStates = {}; // path -> 'processing' | 'valid' | 'invalid'
let nodeRanges = {}; // path -> {low, high}
let callStack = [];
let isValid = null;
let autoRunning = false;
let autoTimer = null;
const width = 750;
const height = 420;
const svg = d3.select("#mainSvg")
.attr("width", width)
.attr("height", height);
function formatBound(val) {
if (val === -Infinity) return "-∞";
if (val === Infinity) return "+∞";
return val;
}
function drawTree(node, x, y, level, path) {
if (!node) return;
const nodeRadius = 28;
const dx = 120 / (level + 1);
const dy = 70;
// Edges
if (node.left) {
svg.append("line")
.attr("x1", x).attr("y1", y + nodeRadius)
.attr("x2", x - dx).attr("y2", y + dy - nodeRadius)
.attr("stroke", "#ddd").attr("stroke-width", 2);
drawTree(node.left, x - dx, y + dy, level + 1, path + 'L');
}
if (node.right) {
svg.append("line")
.attr("x1", x).attr("y1", y + nodeRadius)
.attr("x2", x + dx).attr("y2", y + dy - nodeRadius)
.attr("stroke", "#ddd").attr("stroke-width", 2);
drawTree(node.right, x + dx, y + dy, level + 1, path + 'R');
}
// Node
const state = nodeStates[path];
const range = nodeRanges[path];
let fill = "#e3f2fd", stroke = "#1976d2";
if (state === 'processing') {
fill = "#ffeb3b"; stroke = "#f57c00";
} else if (state === 'valid') {
fill = "#c8e6c9"; stroke = "#4caf50";
} else if (state === 'invalid') {
fill = "#ffcdd2"; stroke = "#e53935";
}
svg.append("circle")
.attr("cx", x).attr("cy", y).attr("r", nodeRadius)
.attr("fill", fill).attr("stroke", stroke).attr("stroke-width", 2);
svg.append("text")
.attr("x", x).attr("y", y + 5)
.attr("text-anchor", "middle")
.attr("font-size", "20px")
.attr("font-weight", "bold")
.text(node.val);
// Range label
if (range) {
const rangeText = `(${formatBound(range.low)}, ${formatBound(range.high)})`;
svg.append("text")
.attr("x", x).attr("y", y + nodeRadius + 15)
.attr("text-anchor", "middle")
.attr("font-size", "10px")
.attr("fill", "#666")
.text(rangeText);
}
}
function draw() {
svg.selectAll("*").remove();
svg.append("text")
.attr("x", width / 2).attr("y", 25)
.attr("text-anchor", "middle")
.attr("font-weight", "bold")
.text(`Validating BST (${useValidTree ? 'Valid' : 'Invalid'} Tree)`);
drawTree(tree, width / 2, 80, 0, 'root');
// Legend
const legend = [
{color: "#e3f2fd", label: "Not visited"},
{color: "#ffeb3b", label: "Processing"},
{color: "#c8e6c9", label: "Valid"},
{color: "#ffcdd2", label: "Invalid"}
];
legend.forEach((item, i) => {
svg.append("rect")
.attr("x", 10 + i * 100).attr("y", height - 30)
.attr("width", 15).attr("height", 15)
.attr("fill", item.color)
.attr("stroke", "#999");
svg.append("text")
.attr("x", 30 + i * 100).attr("y", height - 18)
.attr("font-size", "11px")
.text(item.label);
});
// Result
if (isValid !== null) {
svg.append("rect")
.attr("x", width - 150).attr("y", height - 50)
.attr("width", 140).attr("height", 40)
.attr("rx", 8)
.attr("fill", isValid ? "#c8e6c9" : "#ffcdd2")
.attr("stroke", isValid ? "#4caf50" : "#e53935");
svg.append("text")
.attr("x", width - 80).attr("y", height - 23)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.text(isValid ? "✓ Valid BST" : "✗ Invalid BST");
}
}
function step() {
if (isValid !== null) return false;
if (isValid === false || (callStack.length === 0 && isValid === null && Object.keys(nodeStates).length > 0)) {
if (isValid === null) isValid = true;
document.getElementById("validDisplay").textContent = isValid ? "Yes ✓" : "No ✗";
document.getElementById("status").textContent =
isValid ? "Tree is a valid BST!" : "Tree is NOT a valid BST!";
draw();
return false;
}
if (callStack.length === 0) {
callStack.push({node: tree, path: 'root', low: -Infinity, high: Infinity, phase: 'check'});
}
const {node, path, low, high, phase} = callStack.pop();
if (!node) {
return callStack.length > 0;
}
if (phase === 'check') {
nodeStates[path] = 'processing';
nodeRanges[path] = {low, high};
document.getElementById("currentDisplay").textContent = `Node ${node.val}`;
document.getElementById("rangeDisplay").textContent =
`(${formatBound(low)}, ${formatBound(high)})`;
// Check if node is within valid range
if (node.val <= low || node.val >= high) {
nodeStates[path] = 'invalid';
isValid = false;
document.getElementById("status").textContent =
`Node ${node.val} is NOT in range (${formatBound(low)}, ${formatBound(high)}) - INVALID!`;
} else {
document.getElementById("status").textContent =
`Node ${node.val} is in range (${formatBound(low)}, ${formatBound(high)}) ✓`;
// Schedule children checks
callStack.push({node, path, low, high, phase: 'done'});
if (node.right) {
callStack.push({node: node.right, path: path + 'R', low: node.val, high, phase: 'check'});
}
if (node.left) {
callStack.push({node: node.left, path: path + 'L', low, high: node.val, phase: 'check'});
}
}
} else if (phase === 'done') {
nodeStates[path] = 'valid';
document.getElementById("status").textContent =
`Node ${node.val} and its subtrees are valid!`;
}
draw();
return callStack.length > 0 && isValid !== false;
}
function reset() {
nodeStates = {};
nodeRanges = {};
callStack = [];
isValid = null;
autoRunning = false;
if (autoTimer) clearInterval(autoTimer);
document.getElementById("currentDisplay").textContent = "-";
document.getElementById("rangeDisplay").textContent = "(-∞, +∞)";
document.getElementById("validDisplay").textContent = "-";
document.getElementById("status").textContent = 'Click "Step" to validate the BST';
document.getElementById("autoBtn").textContent = "Auto Run";
draw();
}
function toggleTree() {
useValidTree = !useValidTree;
tree = useValidTree ? validTree : invalidTree;
document.getElementById("toggleTreeBtn").textContent =
`Toggle: ${useValidTree ? 'Valid' : 'Invalid'} Tree`;
reset();
}
function autoRun() {
if (autoRunning) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
} else {
autoRunning = true;
document.getElementById("autoBtn").textContent = "Pause";
const speed = 2100 - document.getElementById("speed").value;
autoTimer = setInterval(() => {
if (!step()) {
autoRunning = false;
clearInterval(autoTimer);
document.getElementById("autoBtn").textContent = "Auto Run";
}
}, speed);
}
}
document.getElementById("stepBtn").addEventListener("click", step);
document.getElementById("autoBtn").addEventListener("click", autoRun);
document.getElementById("resetBtn").addEventListener("click", reset);
document.getElementById("toggleTreeBtn").addEventListener("click", toggleTree);
draw();
</script>
</body>
</html>