xxxxxxxxxx
115
function drawBinaryTree(x, y, height, branchLength, index) {
const stackStart = getNumNodesOnLevel(treeHeight) - 1;
// Draw the current node
fill(0, 0, 255);
textAlign(CENTER, CENTER);
textSize(10);
text(index, x, y - 30);
fill(255);
circle(x, y, 30);
const value = data[index];
if (value == undefined) {
fill(255, 0, 0);
circle(x, y, 30);
} else {
const button = createButton(value.toString());
button.position(x - button.width/2, y - button.height/2);
button.mousePressed(() => changeValue(index));
button.class('unstyled-button');
buttons.push(button)
// fill(0);
// textSize(15);
// text(value, x, y);
if (index >= stackStart) {
fill(255, 0, 255);
textSize(10);
text(index - stackStart, x, y + 30);
}
}
// Base case
if (height <= 1) return;
// Calculate the positions of child nodes
const leftX = x - branchLength;
const rightX = x + branchLength;
const nextY = y + 100;
// Draw lines to connect the current node to its child nodes
line(x, y + 15, leftX, nextY - 15);
line(x, y + 15, rightX, nextY - 15);
// Recursively draw the left and right subtrees
drawBinaryTree(leftX, nextY, height - 1, branchLength / 2, getLeftChildIndex(index));
drawBinaryTree(rightX, nextY, height - 1, branchLength / 2, getRightChildIndex(index));
}
function getLeftChildIndex(i) {
return 2 * i + 1;
}
function getRightChildIndex(i) {
return 2 * i + 2;
}
function isValidNumberSequence(raw) {
// Remove spaces from the input string
const sanitizedInput = raw.replace(/\s/g, '');
// Check if the sanitized input is a sequence of numbers separated by commas
const isValid = /^[0-9]+(,[0-9]+)*$/.test(sanitizedInput);
return isValid;
}
function convertStringToArray(raw) {
// Remove spaces from the input string
const sanitizedInput = raw.replace(/\s/g, '');
// Split the sanitized input into an array using commas as the delimiter
const numberArray = sanitizedInput.split(',');
// Convert each element of the array to a number
const resultArray = numberArray.map(Number);
return resultArray;
}
function isStringInteger(raw) {
// Use parseInt to attempt to convert the string to an integer
let num = parseInt(raw, 10);
// Check if the parsed value is a valid number and if it's equal to the original string
return !isNaN(num) && num.toString() === raw;
}
function watchWarning(selector, isError) {
const warningElement = select(selector);
warningElement.style('display', 'none');
if (isError) {
warningElement.style('display', 'block');
}
return isError; // return true if has errors
}
function changeValue(index) {
const raw = window.prompt("Enter new value:");
if (!raw) return;
if (!isStringInteger(raw)) {
window.alert("Invalid input!");
return;
}
data[index] = parseInt(raw);
const dataInput = select("#heapData");
dataInput.value(data.toString());
const eventObj = {target: {value: data.toString()}}
updateData(eventObj);
}