Spaces:
Runtime error
Runtime error
Commit ·
cf69cfa
1
Parent(s): 2344e49
Added Flask DSA Hub project files
Browse filesFiles changed (28)
- Arrays/README.mdAdded+37
- Arrays/__pycache__/array_app.cpython-312.pycAdded
- Arrays/array_app.pyAdded+72
- Arrays/templates/index.htmlAdded+16
- Arrays/templates/marks.htmlAdded+106
- Arrays/templates/results.htmlAdded+31
- Graphs/README.mdAdded+24
- Graphs/__pycache__/graphs_app.cpython-312.pycAdded
- Graphs/graphs_app.pyAdded+42
- Graphs/templates/graph.htmlAdded+117
- Linked_list/README.mdAdded+28
- Linked_list/__pycache__/playlist_app.cpython-312.pycAdded
- Linked_list/playlist_app.pyAdded+76
- Linked_list/templates/playlist.htmlAdded+114
- Queue/README.mdAdded+30
- Queue/__pycache__/queue_app.cpython-312.pycAdded
- Queue/queue_app.pyAdded+46
- Queue/templates/queue.htmlAdded+52
- Stack/README.mdAdded+22
- Stack/__pycache__/stack_app.cpython-312.pycAdded
- Stack/requirements.txtAdded+1
- Stack/stack_app.pyAdded+26
- Stack/static/style.cssAdded+10
- Stack/templates/stack.htmlAdded+59
- Trees/README.mdAdded+30
- Trees/__pycache__/trees_app.cpython-312.pycAdded
- Trees/templates/tree.htmlAdded+88
- Trees/trees_app.pyAdded+58
12345678910111213141516171819202122232425262728293031323334353637# Student Marks Manager (Arrays)
A Flask-based web application to demonstrate **arrays** using a real-world example: managing student marks. Users can enter marks, and the app calculates statistics like average, highest, lowest, median, pass/fail counts, and score distribution.
---
## 🚀 Features- Input student marks interactively- Display all marks neatly- Calculate: - Average - Highest and lowest - Median - Pass/fail counts - Distribution of scores- Export results to CSV
---
## 📂 Project Structure- `array_app.py` → Flask backend logic- `templates/` → HTML templates (`index.html`, `results.html`,`marks.html`)
---
## ⚙️ Installation1. Clone the repository: ```bash git clone https://github.com/Swetha-ks/student-marks-manager.git cd student-marks-manager
2. pip install -r requirements.txt3. python app.py4. http://127.0.0.1:5000
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172from flask import Blueprint, render_template, request, Responseimport csv, io
# Define the Blueprintarray_app = Blueprint("array_app", __name__, template_folder="templates")
last_results = {}
@array_app.route("/", methods=["GET", "POST"])def index(): if request.method == "POST": n = int(request.form["num_students"]) return render_template("marks.html", num_students=n) return render_template("index.html")
@array_app.route("/results", methods=["POST"])def results(): students = [] n = int(request.form["num_students"]) for i in range(n): name = request.form.get(f"name{i}") mark = int(request.form.get(f"mark{i}")) students.append((name, mark))
marks = [m for (_, m) in students] average = sum(marks) / len(marks) high = max(marks) low = min(marks) pass_count = sum(1 for m in marks if m >= 35) fail_count = len(marks) - pass_count sorted_marks = sorted(marks) median = (sorted_marks[n//2 - 1] + sorted_marks[n//2]) / 2 if n % 2 == 0 else sorted_marks[n//2] ranked = sorted(students, key=lambda x: x[1], reverse=True)
global last_results last_results = { "students": ranked, "average": average, "high": high, "low": low, "median": median, "pass_count": pass_count, "fail_count": fail_count }
return render_template("results.html", students=ranked, average=average, high=high, low=low, pass_count=pass_count, fail_count=fail_count, median=median)
@array_app.route("/download")def download(): output = io.StringIO() writer = csv.writer(output)
writer.writerow(["Rank", "Name", "Mark", "Status"]) for i, (name, mark) in enumerate(last_results["students"], start=1): status = "Pass" if mark >= 35 else "Fail" writer.writerow([i, name, mark, status])
writer.writerow([]) writer.writerow(["Average", last_results["average"]]) writer.writerow(["Highest", last_results["high"]]) writer.writerow(["Lowest", last_results["low"]]) writer.writerow(["Median", last_results["median"]]) writer.writerow(["Pass Count", last_results["pass_count"]]) writer.writerow(["Fail Count", last_results["fail_count"]])
response = Response(output.getvalue(), mimetype="text/csv") response.headers["Content-Disposition"] = "attachment; filename=results.csv" return response
12345678910111213141516<!DOCTYPE html><html><head> <title>Student Count</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"></head><body class="container mt-5"> <h2 class="mb-4">Enter Number of Students</h2> <form method="POST" class="form-inline"> <div class="mb-3"> <input type="number" name="num_students" class="form-control" placeholder="Number of Students" required> </div> <button type="submit" class="btn btn-primary">Next</button> </form></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Student Marks Entry</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet"> <style> body { background: #f4f6f9; font-family: 'Segoe UI', sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; } .form-card { max-width: 800px; width: 100%; background: #fff; border-radius: 12px; box-shadow: 0 6px 20px rgba(0,0,0,0.1); padding: 40px; } .form-header { text-align: center; margin-bottom: 30px; } .form-header h2 { font-weight: bold; color: #0d6efd; } .form-header p { color: #6c757d; } .form-control { border-radius: 8px; padding: 12px; } .btn-custom { border-radius: 8px; padding: 12px 30px; font-size: 16px; font-weight: 600; } .btn-success { background-color: #198754; border: none; } .btn-success:hover { background-color: #157347; } .btn-outline-secondary { border: 2px solid #6c757d; } .btn-outline-secondary:hover { background-color: #6c757d; color: #fff; } </style></head><body>
<div class="form-card"> <!-- Header --> <div class="form-header"> <h2>📋 Student Marks Entry</h2> <p>Please fill in the details below</p> </div>
<!-- Form --> <form method="POST" action="/arrays/results"> <input type="hidden" name="num_students" value="{{ num_students }}">
<div class="row"> {% for i in range(num_students) %} <div class="col-md-6 mb-4"> <div class="border rounded p-3 bg-light"> <h6 class="fw-bold text-secondary mb-3">Student {{ loop.index }}</h6> <div class="mb-3"> <label class="form-label">Name</label> <input type="text" name="name{{ i }}" class="form-control" placeholder="Enter student name" required> </div> <div class="mb-3"> <label class="form-label">Mark</label> <input type="number" name="mark{{ i }}" class="form-control" placeholder="Enter mark" required> </div> </div> </div> {% endfor %} </div>
<!-- Buttons --> <div class="text-center mt-4"> <button type="submit" class="btn btn-success btn-custom me-3 shadow-sm"> <i class="bi bi-check-circle"></i> Submit Marks </button> <button type="reset" class="btn btn-outline-secondary btn-custom shadow-sm"> <i class="bi bi-arrow-counterclockwise"></i> Reset Form </button> </div> </form> </div>
</body></html>12345678910111213141516171819202122232425262728293031<!DOCTYPE html><html><head> <title>Results</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"></head><body class="container mt-5"> <h2 class="mb-4">Gradebook Results</h2> <ul class="list-group mb-4"> {% for name, mark in students %} <li class="list-group-item"> Rank {{ loop.index }}: <strong>{{ name }}</strong> - {{ mark }} <span class="badge bg-{{ 'success' if mark >= 35 else 'danger' }}"> {{ "Pass" if mark >= 35 else "Fail" }} </span> </li> {% endfor %} </ul> <div class="card p-3"> <p><strong>Average:</strong> {{ average }}</p> <p><strong>Highest:</strong> {{ high }}</p> <p><strong>Lowest:</strong> {{ low }}</p> <p><strong>Median:</strong> {{ median }}</p> <p><strong>Pass:</strong> {{ pass_count }}</p> <p><strong>Fail:</strong> {{ fail_count }}</p> </div> <div class="mt-3"> <a href="/" class="btn btn-secondary">Back to Hub</a> </div></body></html>123456789101112131415161718192021222324
---
# Graph Visualizer(Graphs)
A Flask-based web application to demonstrate **graphs**. Users can add nodes and edges, and visualize connections dynamically.
---
## 🚀 Features- Add nodes and edges- Force-directed graph visualization- Drag nodes to rearrange
## 📂 Project Structure- `graphs_app.py` → Flask backend logic- `templates/` → HTML templates (`graph.html`)
## ⚙️ Installation```bashpip install -r requirements.txtpython app.py123456789101112131415161718192021222324252627282930313233343536373839404142from flask import Blueprint, render_template, request, jsonify
graphs_app = Blueprint("graphs_app", __name__, template_folder="templates")
class Graph: def __init__(self): self.graph = {}
def add_edge(self, u, v): if u not in self.graph: self.graph[u] = [] self.graph[u].append(v) # Undirected graph: add reverse if v not in self.graph: self.graph[v] = [] self.graph[v].append(u)
def to_dict(self): nodes = [{"id": node} for node in self.graph] links = [] for u in self.graph: for v in self.graph[u]: links.append({"source": u, "target": v}) return {"nodes": nodes, "links": links}
g = Graph()
@graphs_app.route("/", methods=["GET"])def home(): return render_template("graph.html")
@graphs_app.route("/add_edge", methods=["POST"])def add_edge(): u = request.form.get("u") v = request.form.get("v") if u and v: g.add_edge(u, v) return jsonify({"status": "ok"})
@graphs_app.route("/graph", methods=["GET"])def graph_data(): return jsonify(g.to_dict())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Graph Visualizer</title> <script src="https://d3js.org/d3.v7.min.js"></script> <style> body { font-family: Arial; text-align: center; margin-top: 20px; } svg { border: 1px solid #ccc; margin-top: 20px; } input, button { padding: 8px; margin: 5px; } </style></head><body> <h1>🔗 Graph Visualizer</h1>
<!-- Edge Form --> <form id="edgeForm"> <input type="text" name="u" id="uInput" placeholder="Node U" required> <input type="text" name="v" id="vInput" placeholder="Node V" required> <button type="submit">Add Edge</button> </form>
<!-- Graph Visualization --> <svg id="graph" width="600" height="400"></svg>
<script> const form = document.getElementById("edgeForm"); const svg = d3.select("#graph"); const width = +svg.attr("width"); const height = +svg.attr("height");
form.addEventListener("submit", async (e) => { e.preventDefault(); const u = document.getElementById("uInput").value; const v = document.getElementById("vInput").value; await fetch("/graphs/add_edge", { method: "POST", headers: {"Content-Type": "application/x-www-form-urlencoded"}, body: "u=" + u + "&v=" + v }); document.getElementById("uInput").value = ""; document.getElementById("vInput").value = ""; drawGraph(); });
async function drawGraph() { const res = await fetch("/graphs/graph"); const data = await res.json();
svg.selectAll("*").remove(); // clear old graph if (!data.nodes.length) return;
const simulation = d3.forceSimulation(data.nodes) .force("link", d3.forceLink(data.links).id(d => d.id).distance(100)) .force("charge", d3.forceManyBody().strength(-300)) .force("center", d3.forceCenter(width / 2, height / 2));
const link = svg.append("g") .selectAll("line") .data(data.links) .enter().append("line") .attr("stroke", "black");
const node = svg.append("g") .selectAll("circle") .data(data.nodes) .enter().append("circle") .attr("r", 20) .attr("fill", "lightblue") .call(d3.drag() .on("start", dragstarted) .on("drag", dragged) .on("end", dragended));
const label = svg.append("g") .selectAll("text") .data(data.nodes) .enter().append("text") .attr("dy", 5) .attr("text-anchor", "middle") .text(d => d.id);
simulation.on("tick", () => { link.attr("x1", d => d.source.x) .attr("y1", d => d.source.y) .attr("x2", d => d.target.x) .attr("y2", d => d.target.y);
node.attr("cx", d => d.x) .attr("cy", d => d.y);
label.attr("x", d => d.x) .attr("y", d => d.y); });
function dragstarted(event, d) { if (!event.active) simulation.alphaTarget(0.3).restart(); d.fx = d.x; d.fy = d.y; }
function dragged(event, d) { d.fx = event.x; d.fy = event.y; }
function dragended(event, d) { if (!event.active) simulation.alphaTarget(0); d.fx = null; d.fy = null; } }
drawGraph(); // initial load </script></body></html>12345678910111213141516171819202122232425262728# Playlist Manager (Linked List)
A Python application that demonstrates **Linked Lists** using a real-world example: managing a music playlist. Each song is represented as a node in a linked list, allowing traversal forward and backward just like in actual media players.
---
## 🚀 Features- Add songs dynamically to the playlist- Play the current song- Move to the **next** or **previous** song- Display playlist status in a GUI- Real-world analogy: Spotify/YouTube playlists internally use linked lists
---
## 📂 Project Structure- `playlist.py` → Main Tkinter GUI + linked list logic- `templates` → playlist.html
---
## ⚙️ Installation1. Clone the repository: ```bash git clone https://github.com/Swetha-ks/linkedlist-playlist.git2. pip install -r requirements.txt3. python playlist.py12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576from flask import Blueprint, render_template, request
playlist_app = Blueprint("playlist_app", __name__, template_folder="templates")
class Song: def __init__(self, title): self.title = title self.next = None self.prev = None
class CircularPlaylist: def __init__(self): self.current = None
def add_song(self, title): new_song = Song(title) if self.current is None: self.current = new_song new_song.next = new_song new_song.prev = new_song else: last = self.current.prev last.next = new_song new_song.prev = last new_song.next = self.current self.current.prev = new_song
def play(self): if self.current: return f"🎶 Now Playing: {self.current.title}" return "No songs in playlist."
def next_song(self): if self.current: self.current = self.current.next return self.play()
def prev_song(self): if self.current: self.current = self.current.prev return self.play()
def get_playlist(self): if not self.current: return [] temp = self.current songs = [] while True: songs.append(temp.title) temp = temp.next if temp == self.current: break return songs
playlist = CircularPlaylist()
@playlist_app.route("/", methods=["GET", "POST"])def playlist_index(): if request.method == "POST": title = request.form["song"] playlist.add_song(title) songs = playlist.get_playlist() status = playlist.play() return render_template("playlist.html", songs=songs, status=status)
@playlist_app.route("/next")def playlist_next(): status = playlist.next_song() songs = playlist.get_playlist() return render_template("playlist.html", songs=songs, status=status)
@playlist_app.route("/prev")def playlist_prev(): status = playlist.prev_song() songs = playlist.get_playlist() return render_template("playlist.html", songs=songs, status=status)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Circular Playlist</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet"> <style> body { background: #f4f6f9; font-family: 'Segoe UI', sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; } .playlist-card { max-width: 600px; width: 100%; background: #fff; border-radius: 12px; box-shadow: 0 6px 20px rgba(0,0,0,0.1); padding: 30px; text-align: center; } .playlist-card h2 { color: #0d6efd; font-weight: bold; margin-bottom: 20px; } .form-control { border-radius: 8px; padding: 12px; } .btn-custom { border-radius: 8px; padding: 10px 25px; font-size: 15px; font-weight: 600; margin: 5px; } .btn-primary { background-color: #0d6efd; border: none; } .btn-primary:hover { background-color: #0b5ed7; } .btn-success { background-color: #198754; border: none; } .btn-success:hover { background-color: #157347; } .btn-secondary { background-color: #6c757d; border: none; } .btn-secondary:hover { background-color: #5c636a; } ul { list-style: none; padding: 0; } ul li { background: #f8f9fa; margin: 5px 0; padding: 8px; border-radius: 6px; } </style></head><body>
<div class="playlist-card"> <h2>🎵 Circular Playlist</h2>
<!-- Add Song Form --> <form method="POST" class="mb-4 d-flex justify-content-center"> <input type="text" name="song" class="form-control me-2" placeholder="Enter song title" required> <button type="submit" class="btn btn-success btn-custom"> <i class="bi bi-plus-circle"></i> Add Song </button> </form>
<!-- Status --> <p class="fw-semibold text-primary">{{ status }}</p>
<!-- Playlist --> <h4 class="mt-3">Playlist</h4> <ul class="mb-4"> {% for s in songs %} <li>{{ s }}</li> {% endfor %} </ul>
<!-- Controls --> <div class="mt-3"> <a href="/playlist/next" class="btn btn-primary btn-custom"> ▶ Next </a> <a href="/playlist/prev" class="btn btn-primary btn-custom"> ⏮ Previous </a> <a href="/" class="btn btn-secondary btn-custom"> ⬅ Back to Hub </a> </div> </div>
</body></html>123456789101112131415161718192021222324252627282930# Customer Service Queue (Queues)
A Flask-based web application that demonstrates the **Queue (FIFO)** data structure using a real-world example: managing a customer service line. Customers join the queue, and the system serves them in the order they arrived.
---
## 🚀 Features- Add customers to the queue (Enqueue)- Serve customers one by one (Dequeue)- Display the current queue in real time- Real-world analogy: ticket counters, call centers, customer service desks
---
## 📂 Project Structure- `queue_app.py` → Flask backend logic- `templates/` → HTML templates (`queue.html`)- `README.md` → Documentation
---
## ⚙️ Installation1. Clone the repository: ```bash git clone https://github.com/Swetha-ks/customer-service-queue.git2. pip install -r requirements.txt3. python app.py
12345678910111213141516171819202122232425262728293031323334353637383940414243444546from flask import Blueprint, render_template, request, redirect, url_for
queue_app = Blueprint("queue_app", __name__, template_folder="templates")
# Queue data structureclass CustomerServiceQueue: def __init__(self): self.queue = []
def arrive(self, customer_name): self.queue.append(customer_name)
def serve(self): if not self.is_empty(): return self.queue.pop(0) return None
def peek(self): if not self.is_empty(): return self.queue[0] return None
def is_empty(self): return len(self.queue) == 0
def get_queue(self): return self.queue
# Global queue instancecsq = CustomerServiceQueue()
@queue_app.route("/")def home(): return render_template("queue.html", queue=csq.get_queue(), next_customer=csq.peek())
@queue_app.route("/arrive", methods=["POST"])def arrive(): name = request.form.get("name") if name: csq.arrive(name) return redirect(url_for("queue_app.home"))
@queue_app.route("/serve")def serve(): csq.serve() return redirect(url_for("queue_app.home"))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Customer Service Queue</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"></head><body class="bg-light">
<div class="container mt-5"> <div class="card shadow-sm"> <div class="card-header bg-success text-white"> <h3 class="mb-0">Customer Service Queue</h3> </div> <div class="card-body">
<!-- Form to add customer --> <form action="/queue/arrive" method="POST" class="d-flex mb-3"> <input type="text" name="name" class="form-control me-2" placeholder="Enter customer name" required> <button type="submit" class="btn btn-primary">Join Queue</button> </form>
<!-- Queue Display --> <h5>📂 Current Queue:</h5> <ul class="list-group mb-3"> {% for customer in queue %} <li class="list-group-item">{{ customer }}</li> {% else %} <li class="list-group-item text-muted">No customers in queue</li> {% endfor %} </ul>
<!-- Next Customer --> {% if next_customer %} <div class="alert alert-info"> Next to be served: <strong>{{ next_customer }}</strong> </div> <a href="/queue/serve" class="btn btn-success">✅ Serve Customer</a> {% else %} <p class="text-muted">No customers waiting.</p> {% endif %}
<div class="mt-3"> <a href="/" class="btn btn-secondary">Back to Hub</a> </div>
</div> </div></div>
</body></html>12345678910111213141516171819202122# Stack Simulator (Flask Project)
A simple web app to demonstrate **stack operations (Push, Pop, Peek)** using Python + Flask.
## 🚀Features- Push items into the stack- Pop items from the stack- Peek at the top element- Clean Bootstrap UI
## 📂Project Structure- Backend: Python (Flask)- Frontend: HTML + Bootstrap
## ⚙️Run Locally```bashgit clone https://github.com/Swetha-ks/stack-simulator.gitcd stack-simulatorpip install -r requirements.txtpython app.pyhttp://127.0.0.1:5000
1Flask==3.0.01234567891011121314151617181920212223242526from flask import Blueprint, render_template, request
stack_app = Blueprint("stack_app", __name__, template_folder="templates")
stack = []
@stack_app.route("/", methods=["GET"])def index(): return render_template("stack.html", stack=stack)
@stack_app.route("/push", methods=["POST"])def push(): item = request.form["item"] stack.append(item) return render_template("stack.html", stack=stack)
@stack_app.route("/pop")def pop(): if stack: stack.pop() return render_template("stack.html", stack=stack)
@stack_app.route("/peek")def peek(): top = stack[-1] if stack else None return render_template("stack.html", stack=stack, top=top)12345678910body { background-color: #f3e8ff; /* soft lavender */}.card-header { background-color: #b57edc; /* lavender purple */}.btn-success { background-color: #9b59b6; /* deep lavender */ border: none;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Stack Simulator</title> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"></head><body class="bg-light">
<div class="container mt-5"> <div class="card shadow-sm"> <div class="card-header bg-primary text-white"> <h3 class="mb-0">Stack Simulator</h3> </div> <div class="card-body">
<!-- Stack Display --> <h5 class="mb-3">Current Stack:</h5> <ul class="list-group mb-3"> {% for item in stack %} <li class="list-group-item">{{ item }}</li> {% else %} <li class="list-group-item text-muted">Stack is empty</li> {% endfor %} </ul>
<!-- Top Element --> {% if top %} <div class="alert alert-info"> Top element: <strong>{{ top }}</strong> </div> {% endif %}
<!-- Push Form --> <form action="/stack/push" method="post" class="d-flex mb-3"> <input type="text" name="item" class="form-control me-2" placeholder="Enter item"> <button type="submit" class="btn btn-success">Push</button> </form>
<!-- Action Buttons --> <div class="d-flex gap-2"> <a href="/stack/pop" class="btn btn-danger">Pop</a> <a href="/stack/peek" class="btn btn-warning">Peek</a> </div>
<div class="mt-3"> <a href="/" class="btn btn-secondary">Back to Hub</a> </div>
</div> </div> </div>
<!-- Bootstrap JS --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script></body></html>123456789101112131415161718192021222324252627282930# Binary Search Tree Visualizer (Trees)
A Flask-based web application to demonstrate the **Binary Search Tree (BST)** data structure. Users can insert nodes and see the tree grow interactively, with parent-child relationships displayed visually.
---
## 🚀 Features- Insert nodes into the BST- Visualize the tree structure dynamically- Show parent-child relationships with edges- Display sorted order using inorder traversal- Real-world analogy: file systems, organizational hierarchies
---
## 📂 Project Structure- `app.py` → Flask backend logic- `templates/` → HTML templates (`tree.html`)
---
## ⚙️ Installation1. Clone the repository: ```bash git clone https://github.com/Swetha-ks/bst-visualizer.git2. pip install -r requirements.txt3. python app.py4. http://127.0.0.1:5000
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>BST Visualizer</title> <script src="https://d3js.org/d3.v7.min.js"></script> <style> body { font-family: Arial; text-align: center; margin-top: 20px; } svg { border: 1px solid #ccc; margin-top: 20px; } input, button { padding: 8px; margin: 5px; } </style></head><body> <h1>🌳 Binary Search Tree Visualizer</h1>
<!-- Insert Form --> <form id="insertForm"> <input type="number" name="value" id="valueInput" placeholder="Enter number" required> <button type="submit">Insert Node</button> </form>
<!-- Tree Visualization --> <div id="tree"></div>
<script> const form = document.getElementById("insertForm");
form.addEventListener("submit", async (e) => { e.preventDefault(); const value = document.getElementById("valueInput").value; await fetch("/trees/insert", { method: "POST", headers: {"Content-Type": "application/x-www-form-urlencoded"}, body: "value=" + value }); document.getElementById("valueInput").value = ""; updateTree(); });
async function updateTree() { const res = await fetch("/trees/tree"); const data = await res.json();
d3.select("#tree").html(""); // clear old tree if (!data) return;
const width = 600, height = 400; const svg = d3.select("#tree").append("svg") .attr("width", width).attr("height", height);
const root = d3.hierarchy(data); const treeLayout = d3.tree().size([width - 100, height - 100]); treeLayout(root);
// Links svg.selectAll("line") .data(root.links()) .enter().append("line") .attr("x1", d => d.source.x + 50) .attr("y1", d => d.source.y + 50) .attr("x2", d => d.target.x + 50) .attr("y2", d => d.target.y + 50) .attr("stroke", "black");
// Nodes svg.selectAll("circle") .data(root.descendants()) .enter().append("circle") .attr("cx", d => d.x + 50) .attr("cy", d => d.y + 50) .attr("r", 20) .attr("fill", "lightblue");
// Labels svg.selectAll("text") .data(root.descendants()) .enter().append("text") .attr("x", d => d.x + 50) .attr("y", d => d.y + 50) .attr("dy", 5) .attr("text-anchor", "middle") .text(d => d.data.name); }
updateTree(); // initial load </script></body></html>12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758from flask import Blueprint, render_template, request, jsonify
trees_app = Blueprint("trees_app", __name__, template_folder="templates")
class Node: def __init__(self, key): self.key = key self.left = None self.right = None
class BST: def __init__(self): self.root = None
def insert(self, key): if self.root is None: self.root = Node(key) else: self._insert(self.root, key)
def _insert(self, root, key): if key < root.key: if root.left is None: root.left = Node(key) else: self._insert(root.left, key) else: if root.right is None: root.right = Node(key) else: self._insert(root.right, key)
def to_dict(self, root): if root is None: return None children = [] if root.left: children.append(self.to_dict(root.left)) if root.right: children.append(self.to_dict(root.right)) return {"name": root.key, "children": children}
bst = BST()
@trees_app.route("/", methods=["GET"])def home(): return render_template("tree.html")
@trees_app.route("/insert", methods=["POST"])def insert(): value = request.form.get("value") if value: bst.insert(int(value)) return jsonify({"status": "ok"})
@trees_app.route("/tree", methods=["GET"])def tree(): return jsonify(bst.to_dict(bst.root))Arrays/README.mdAdded+37
Arrays/__pycache__/array_app.cpython-312.pycAdded
Arrays/array_app.pyAdded+72
Arrays/templates/index.htmlAdded+16
Arrays/templates/marks.htmlAdded+106
Arrays/templates/results.htmlAdded+31
Graphs/README.mdAdded+24
Graphs/__pycache__/graphs_app.cpython-312.pycAdded
Graphs/graphs_app.pyAdded+42
Graphs/templates/graph.htmlAdded+117
Linked_list/README.mdAdded+28
Linked_list/__pycache__/playlist_app.cpython-312.pycAdded
Linked_list/playlist_app.pyAdded+76
Linked_list/templates/playlist.htmlAdded+114
Queue/README.mdAdded+30
Queue/__pycache__/queue_app.cpython-312.pycAdded
Queue/queue_app.pyAdded+46
Queue/templates/queue.htmlAdded+52
Stack/README.mdAdded+22
Stack/__pycache__/stack_app.cpython-312.pycAdded
Stack/requirements.txtAdded+1
Stack/stack_app.pyAdded+26
Stack/static/style.cssAdded+10
Stack/templates/stack.htmlAdded+59
Trees/README.mdAdded+30
Trees/__pycache__/trees_app.cpython-312.pycAdded
Trees/templates/tree.htmlAdded+88
Trees/trees_app.pyAdded+58