Understanding Trees and Graphs in Java: Exploring the Application and Implementation of Nonlinear Data Structures
class Node { int data; Node left; Node right; public Node(int item) { data = item; left = right = null; } } class BinarySearchTree { Node root; public BinarySearchTree() { root = null; } public void insert(int data) { root = insertRec(root, data); } private Node insertRec(Node root, int data) { if (root == null) { root = new Node(data); return root; } if (data < root.data) root.left = insertRec(root.left, data); else if (data > root.data) root.right = insertRec(root.right, data); return root; } public boolean search(int data) { return searchRec(root, data); } private boolean searchRec(Node root, int data) { if (root == null) return false; if (data == root.data) return true; if (data < root.data) return searchRec(root.left, data); return searchRec(root.right, data); } } public class Main { public static void main(String[] args) { BinarySearchTree bst = new BinarySearchTree(); bst.insert(50); bst.insert(30); bst.insert(70); bst.insert(20); bst.insert(40); bst.insert(60); bst.insert(80); System.out.println("Is 20 present? " + bst.search(20)); System.out.println("Is 100 present? " + bst.search(100)); } }
In the above example, we define a Node class to represent the nodes of the binary tree, and the BinarySearchTree class to represent the binary search Tree. We can use the insert method to insert elements into the tree and the search method to search for elements.
import java.util.*; class Graph { private int V; private LinkedList<Integer>[] adjList; public Graph(int v) { V = v; adjList = new LinkedList[v]; for (int i = 0; i < v; ++i) adjList[i] = new LinkedList(); } void addEdge(int v, int w) { adjList[v].add(w); } void BFS(int s) { boolean[] visited = new boolean[V]; LinkedList<Integer> queue = new LinkedList<Integer>(); visited[s] = true; queue.add(s); while (queue.size() != 0) { s = queue.poll(); System.out.print(s + " "); Iterator<Integer> i = adjList[s].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) { visited[n] = true; queue.add(n); } } } } } public class Main { public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println("BFS traversal starting from vertex 2:"); g.BFS(2); } }
In the above example, we use an adjacency linked list to represent the data structure of the graph. We define the Graph class, in which the addEdge method is used to add edges and the BFS method is used to perform breadth-first search traversal. In the example, we do a BFS traversal starting from vertex 2 and print out the traversal order.
The above is the detailed content of In-depth exploration of the application and implementation methods of non-linear data structures of trees and graphs in Java. For more information, please follow other related articles on the PHP Chinese website!