Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
My journey with you | All you wish will be here !!!
My journey with you | All you wish will be here !!!
Introduction to Trees
Trees, in the realm of computer science, are a fundamental data structure that can be visualized as a hierarchical structure with nodes connected by edges. They are often used to represent hierarchical relationships, such as file systems, organizational charts, or decision-making processes.
Key Properties of Trees:
Binary Trees vs. Binary Search Trees
While both binary trees and binary search trees are types of trees, they differ in their structure and operations.
Binary Tree:
Binary Search Tree (BST):
Basic Operations on Trees
Example of a Binary Search Tree
Opens in a new window courses.grainger.illinois.edu
binary search tree with nodes containing numbers
Code Implementation (Java)
Java
class Node {
int data;
Node left, right;
public Node(int item) {
data = item;
left = right = null;
}
}
class BinarySearchTree {
Node root;
public BinarySearchTree() {
root = null;
}
void insert(int data) {
root = insertRec(root, data);
}
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;
}
void inorderTraversal() {
inorderTraversalRec(root);
}
void inorderTraversalRec(Node root) {
if (root != null) {
inorderTraversalRec(root.left);
System.out.print(root.data + " ");
inorderTraversalRec(root.right);
}
}
}
public class Main {
public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();
tree.insert(50);
tree.insert(30);
tree.insert(70);
tree.insert(20);
tree.insert(40);
tree.insert(60);
tree.insert(80);
System.out.println("In-order traversal:");
tree.inorderTraversal();
}
}
Use code with caution.
Conclusion
Trees are versatile data structures that have numerous applications in computer science. Understanding the concepts of trees, especially binary trees and binary search trees, is essential for building efficient algorithms and solving various problems. By mastering the basic operations of insertion and traversal, you can effectively work with trees in your programming endeavors.
Keywords: trees, binary trees, binary search trees, data structure, insertion, traversal, pre-order, in-order, post-order, root node, leaf nodes, parent node, child node, subtree, Java, code example.
Also see: The Z Blogs
my other Blog: The Z Blog ZB