0% found this document useful (0 votes)
8 views8 pages

Dsa Note

The document contains Java code for various data structures and algorithms, including binary search trees (BST), graph cycles, and tree traversal methods. It includes methods for printing even values, calculating tree height, and performing basic operations like insertion, deletion, and searching in a BST. Additionally, it features cycle detection in graphs and provides example usage of these data structures and algorithms.

Uploaded by

anhkolo09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views8 pages

Dsa Note

The document contains Java code for various data structures and algorithms, including binary search trees (BST), graph cycles, and tree traversal methods. It includes methods for printing even values, calculating tree height, and performing basic operations like insertion, deletion, and searching in a BST. Additionally, it features cycle detection in graphs and provides example usage of these data structures and algorithms.

Uploaded by

anhkolo09
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

import [Link].

Queue; } public static void


printNodesLevelByLevel(TreeNode root) {
import [Link]; printEvenValuesHelper([Link]);
if (root == null) {
class TreeNode { if ([Link] % 2 == 0) {
return;
int data; [Link]([Link] + " ");
}
TreeNode left, right; }
Queue<TreeNode> queue = new
public TreeNode(int data) { printEvenValuesHelper([Link]);
LinkedList<>();
[Link] = data; }
[Link](root);
[Link] = [Link] = null;
// b. Takes the root of a while (![Link]()) {
}
binary search tree and finds int levelSize = [Link]();
}
the height of the tree for (int i = 0; i < levelSize; i++) {
public class BSTAlgorithms {
public static int getHeight(TreeNode root) { TreeNode node = [Link]();

// a. Takes the root of a if (root == null) { [Link]([Link] + " ");

binary search tree and prints return 0; if ([Link] != null) {

all even values in the tree. } [Link]([Link]);

public static void int leftHeight = getHeight([Link]); }


findAndPrintEvenValues(TreeNode root) {
int rightHeight = getHeight([Link]); if ([Link] != null) {
printEvenValuesHelper(root);
return [Link](leftHeight, rightHeight) [Link]([Link]);
} + 1;
}
private static void }
}
printEvenValuesHelper(TreeNode node) {

if (node == null) {
// c. Takes the root of a [Link](); // New line after
each level
return;
binary search tree and runs
}
BFS to print nodes level by.
} public static void printAllKeys(Node root) { TreeNode left, right;

} if (root == null) { public TreeNode(int data) {

return; [Link] = data;


non-recursive in tất cả key
} [Link] = [Link] = null;
của cây dùng biểu diễn left-
Queue<Node> queue = new }
child, right-sibling LinkedList<>();
}
import [Link]; [Link](root);
public class BSTSumOdd {
import [Link]; while (![Link]()) {
public static int sumOddValues(TreeNode
class Node { Node current = [Link](); root) {
Object key; // Assuming general Object for [Link]([Link] + " "); return sumOddHelper(root);
key (e.g., Character for A, B, etc.)
Node child = current.left_child; }
Node left_child;
while (child != null) { private static int sumOddHelper(TreeNode
Node right_sibling; node) {
[Link](child);
Node parent; // Included as per description, if (node == null) {
though not used in printing child = child.right_sibling;
return 0;
public Node(Object key) { }
}
[Link] = key; }
int sum = 0;
this.left_child = null; [Link]();
sum += sumOddHelper([Link]);
this.right_sibling = null; }
if ([Link] % 2 != 0) { // Check if odd
[Link] = null; }
sum += [Link];
} Binary tree }
} class TreeNode {
sum += sumOddHelper([Link]);
public class TreePrinter { int data;
return sum;
} dfsCycles(start, visited, path, start);
find backward edges
} }
import [Link].*;
private void dfsCycles(int u, boolean[]
Find cycle visited, Deque<Integer> path, int start) { public class GraphBackwardEdges {
import [Link].*;
visited[u] = true;
private int V;
public class GraphCycles {
[Link](u);
private List<Integer>[] adj;
private int V; // Number of vertices
for (int v : adj[u]) {
private List<Integer>[] adj; // Adjacency list @SuppressWarnings("unchecked")
if (!visited[v]) {
@SuppressWarnings("unchecked") public GraphBackwardEdges(int vertices) {
dfsCycles(v, visited, path, start);
public GraphCycles(int vertices) {
} else if (v == start && [Link]() > 2) V = vertices;
V = vertices; { // Cycle back to start, min length 3
adj = new ArrayList[V];
adj = new ArrayList[V]; // Print the cycle

[Link]("Cycle: "); for (int i = 0; i < V; i++) {


for (int i = 0; i < V; i++) {

adj[i] = new ArrayList<>(); for (int node : path) { adj[i] = new ArrayList<>();

} [Link](node + " "); }


} }
}
public void addEdge(int u, int v) { [Link]("-> " + v); //
Close the cycle public void addEdge(int u, int v) {
adj[u].add(v); // Directed edge
} adj[u].add(v); // Directed
}
}
public void printAllSimpleCycles(int start) { }
[Link]();
boolean[] visited = new boolean[V];
visited[u] = false;}
Deque<Integer> path = new
public void findBackwardEdges(int start) {
ArrayDeque<>();
boolean[] visited = new boolean[V]; recStack[u] = false; }

boolean[] recStack = new boolean[V]; // return false; }


Recursion stack to check ancestors
}
dfsBackward(start, visited, recStack);
public class BinarySearchTree {
}
// Binary Search Tree (BST)
private TreeNode root;
private boolean dfsBackward(int u, boolean[] Includes: Insert, Delete,
visited, boolean[] recStack) {
Search, Inorder, Preorder,
visited[u] = true; Postorder traversals, and public BinarySearchTree() {
basic operations like find
recStack[u] = true; [Link] = null;
min/max
for (int v : adj[u]) { }

if (!visited[v]) {
class TreeNode {
if (dfsBackward(v, visited, recStack))
{ int data; // Insert a node
return true; // Cycle detected, but TreeNode left; public void insert(int data) {
continue for all edges
TreeNode right; root = insertRecursive(root, data);
}
}
} else if (recStack[v])
public TreeNode(int data) {
[Link]("Backward edge: "
+ u + " -> " + v); [Link] = data; private TreeNode insertRecursive(TreeNode
node, int data) {
} [Link] = null;
if (node == null) {
} [Link] = null;
return new TreeNode(data);
} } return node;

if (data < [Link]) { if (data < [Link]) { }

[Link] = insertRecursive([Link], [Link] = deleteRecursive([Link],


data); data);

} else if (data > [Link]) { } else if (data > [Link]) {


// Search for a node
[Link] = insertRecursive([Link], [Link] = deleteRecursive([Link], public boolean search(int data) {
data); data);
return searchRecursive(root, data);
} } else {
}
return node; // Ignore duplicates // Node with one child or no child

} if ([Link] == null) {
private boolean searchRecursive(TreeNode
return [Link]; node, int data) {

} else if ([Link] == null) { if (node == null) {


// Delete a node
return [Link]; return false;
public void delete(int data) {
} }
root = deleteRecursive(root, data);
// Node with two children: Get the if (data == [Link]) {
} inorder successor (smallest in the right subtree)
return true;
[Link] = findMin([Link]).data;
}
private TreeNode deleteRecursive(TreeNode // Delete the inorder successor
node, int data) { return data < [Link] ?
[Link] = deleteRecursive([Link], searchRecursive([Link], data) :
if (node == null) { [Link]); searchRecursive([Link], data);

return null; } }
public void preorder() { }

preorderRecursive(root);
// Inorder traversal (Left,
Root, Right) - Sorted order [Link](); private void postorderRecursive(TreeNode
node) {
public void inorder() { }
if (node != null) {
inorderRecursive(root);
postorderRecursive([Link]);
[Link](); private void preorderRecursive(TreeNode
node) { postorderRecursive([Link]);
}
if (node != null) { [Link]([Link] + " ");

[Link]([Link] + " "); }


private void inorderRecursive(TreeNode
node) { preorderRecursive([Link]); }

if (node != null) { preorderRecursive([Link]);

inorderRecursive([Link]); }
// Basic operations: Find
[Link]([Link] + " "); } minimum value
inorderRecursive([Link]); public TreeNode findMin() {

} return findMin(root);
// Postorder traversal (Left,
} Right, Root) }

public void postorder() {

postorderRecursive(root); private TreeNode findMin(TreeNode node) {


// Preorder traversal (Root,
Left, Right) [Link](); if (node == null) {
return null; while ([Link] != null) { [Link]();

} node = [Link];

while ([Link] != null) { } [Link]("Preorder traversal:");

node = [Link]; return node; [Link]();

} }

return node; [Link]("Postorder traversal:");

} [Link]();
// Example usage
public static void main(String[] args) {
// Search
// Basic operations: Find BinarySearchTree bst = new
BinarySearchTree();
maximum value [Link]("Search for 70: " +
[Link](70)); // true
public TreeNode findMax() {
[Link]("Search for 100: " +
// Insert nodes (example from one of the [Link](100)); // false
return findMax(root); exams: 40, 80, 25, 70, 6, 8, 27, 50, etc.)

} int[] items = {40, 80, 25, 70, 6, 8, 27, 50,


40, 25, 52, 30, 27, 41, 88, 90};
// Delete
for (int item : items) {
private TreeNode findMax(TreeNode node) [Link](40); // Delete root
{ [Link](item);
[Link]("Inorder after deleting
if (node == null) { 40:");
}

return null; [Link]();

} [Link]("Inorder traversal:");
// Min and Max

[Link]("Min value: " +


[Link]().data);

[Link]("Max value: " +


[Link]().data);

You might also like