Skip to content

Commit d52bf68

Browse files
committed
Binary Tree and Choosing the right DS
1 parent 67843b8 commit d52bf68

File tree

3 files changed

+328
-0
lines changed

3 files changed

+328
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
This repository contains various data structures and provide insights about them. Below topics/problems are covered as of now.
33

44
**1. Arrays**
5+
- [ ] Choosing the right data structure
56
- [X] [Introduction to Arrays](../master/src/com/deepak/data/structures/Arrays/Introduction.md)
67
- [X] [Basic operations on Arrays](../master/src/com/deepak/data/structures/Arrays/BasicOperations.java)
78

@@ -27,6 +28,8 @@ This repository contains various data structures and provide insights about them
2728
- [ ] Stack based Implementation
2829
- [X] [Dequeue](../master/src/com/deepak/data/structures/Queue/Dequeue.java)
2930
- [ ] Priority Queue
31+
- [ ] Implement Stack using Queues
32+
- [ ] Implement Queue using Stacks
3033

3134
**5. Trees**
3235
- [ ] Introduction
Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
package com.deepak.data.structure.Tree;
2+
3+
import java.util.LinkedList;
4+
import java.util.Queue;
5+
6+
public class BinaryTree {
7+
8+
public static void main(String[] args) {
9+
BinaryTree tree = new BinaryTree();
10+
System.out.println("Initial Size of Tree => " + tree.size());
11+
tree.addNode(10);
12+
System.out.println("Inserted 10");
13+
System.out.println("Size of tree after insertion => " + tree.size());
14+
System.out.println("Printing the Tree");
15+
printByLevel(root);
16+
System.out.println();
17+
tree.addNode(7);
18+
tree.addNode(12);
19+
tree.addNode(13);
20+
tree.addNode(8);
21+
tree.addNode(15);
22+
tree.addNode(9);
23+
System.out.println("Size of tree after insertion => " + tree.size());
24+
System.out.println("Printing the Tree");
25+
System.out.println();
26+
printByLevel(root);
27+
}
28+
29+
static Node root;
30+
int size = 0;
31+
32+
public void addNode(int value) {
33+
if (size == 0) {
34+
root = new Node(value);
35+
size++;
36+
} else {
37+
addNode(root, value);
38+
}
39+
}
40+
41+
private Node addNode(Node rootNode, int value) {
42+
if (rootNode == null) {
43+
return null;
44+
}
45+
Node newNode = new Node(value);
46+
if (rootNode.left == null) {
47+
rootNode.left = new Node(value);
48+
} else if (rootNode.left != null && newNode.data <= rootNode.data) {
49+
rootNode.left = addNode(rootNode.left, value);
50+
} else if (rootNode.right == null && newNode.data > rootNode.data) {
51+
rootNode.right = new Node(value);
52+
} else if (rootNode.right != null) {
53+
rootNode.right = addNode(rootNode.right, value);
54+
}
55+
size++;
56+
return rootNode;
57+
}
58+
59+
public Node root() {
60+
if (isEmpty()) {
61+
return null;
62+
} else {
63+
return root;
64+
}
65+
}
66+
67+
public boolean isEmpty() {
68+
return size == 0;
69+
}
70+
71+
public int size() {
72+
return size;
73+
}
74+
75+
public boolean isRoot(Node node) {
76+
if (root == node) {
77+
return true;
78+
}
79+
return false;
80+
}
81+
82+
public Node findParent(Node node) {
83+
return findParent(node.data, root, null);
84+
}
85+
86+
private Node findParent(int data, Node root, Node parent) {
87+
if (root == null) {
88+
return null;
89+
}
90+
if (root.data != data) {
91+
parent = findParent(data, root.left, root);
92+
if (parent == null) {
93+
parent = findParent(data, root.right, root);
94+
}
95+
}
96+
return parent;
97+
}
98+
99+
public boolean hasParent(Node node) {
100+
return findParent(node) != null;
101+
}
102+
103+
public boolean hasLeft(Node node) {
104+
return node.left != null;
105+
}
106+
107+
public Node left(Node node) {
108+
if (hasLeft(node)) {
109+
return node.left;
110+
}
111+
return null;
112+
}
113+
114+
public boolean hasRight(Node node) {
115+
return node.right != null;
116+
}
117+
118+
public Node right(Node node) {
119+
if (hasRight(node)) {
120+
return node.right;
121+
}
122+
return null;
123+
}
124+
125+
public boolean isLeaf(Node node) {
126+
return !hasLeft(node) && !hasRight(node);
127+
}
128+
129+
public int getLevel() {
130+
return (int)(Math.log(size) / Math.log(2));
131+
}
132+
133+
public static void printInOrder(Node node) {
134+
if (node == null) {
135+
return;
136+
}
137+
printInOrder(node.left);
138+
System.out.print(node.data + " ");
139+
printInOrder(node.right);
140+
}
141+
142+
public static void printPreorder(Node node) {
143+
if (node == null) return;
144+
System.out.print(node.data + " ");
145+
printPreorder(node.left);
146+
printPreorder(node.right);
147+
}
148+
149+
public static void printPostorder(Node node) {
150+
if (node == null) return;
151+
printPostorder(node.left);
152+
printPostorder(node.right);
153+
System.out.print(node.data + " ");
154+
}
155+
156+
public static void printByLevel(Node root) {
157+
Queue<Node> firstQ = new LinkedList<>();
158+
firstQ.add(root);
159+
160+
Queue<Queue<Node>> mainQ = new LinkedList<>();
161+
mainQ.add(firstQ);
162+
163+
while (!mainQ.isEmpty()) {
164+
Queue<Node> levelQ = mainQ.remove();
165+
Queue<Node> nextLevelQ = new LinkedList<>();
166+
for (Node x : levelQ) {
167+
System.out.print(x.data + " ");
168+
if (x.left != null) nextLevelQ.add(x.left);
169+
if (x.right != null) nextLevelQ.add(x.right);
170+
}
171+
if (!nextLevelQ.isEmpty()) mainQ.add(nextLevelQ);
172+
System.out.println();
173+
}
174+
}
175+
176+
public class Node {
177+
178+
private Node left;
179+
private Node right;
180+
private int data;
181+
182+
public Node(int data) {
183+
this.data = data;
184+
}
185+
186+
@Override
187+
public String toString() {
188+
return "Node [data=" + data + "]";
189+
}
190+
191+
}
192+
193+
}
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
Choosing the right data structure :
2+
3+
Data structure is the way how data is stored in the computer. Developer should choose data structure very wisely else system will not perform well.
4+
Below are the bunch of DS and reasons when to use which one.
5+
6+
1. Array
7+
- Data Structure used to store similar kind of elements in contiguous memory. Can be used in below cases,
8+
a) Fast element access is needed (Can be done using the index)
9+
b) When number of elements i.e size of array is known before hand
10+
c) When iterating through all the elements in sequence is needed
11+
d) When less memory has to be used. (Arrays take less memory as compared to LinkedList)
12+
13+
2. Singly Linked List
14+
- Data Structure used to store data in nodes, and nodes are connected to each other pointing in one direction. Can be used in below cases,
15+
a) When constant time of insertion and deletion is needed (On head)
16+
b) When data dynamically grows
17+
c) When random elements are not needed to be accessed
18+
d) When insertion is needed at any point in the list
19+
20+
3. Doubly Linked List
21+
- Data Structure used to store data in nodes, and those nodes are connected to each other pointing in both the directions. Can be used in below cases,
22+
a) It's easier to delete the node from doubly linked list
23+
b) Can be iterated in reverse order without recursion
24+
c) Insert or remove from doubly linked list is faster.
25+
26+
4. Circular Linked List
27+
- Data Structure used to store data in nodes, and nodes point to next node in one direction except the last node, which again points to first node. Can be used in below cases,
28+
a) Develop the buffer memory
29+
b) Represent a deck of cards in a game
30+
c) Browser cache which allows to hit the back button
31+
d) MRU list (Most recently used list)
32+
e) Undo functionality in photoshop or word
33+
34+
5. Stack
35+
- Data Structure which stores the data in LIFO form i.e LAST IN FIRST OUT. Think of a stack of plates. Can be used in below cases,
36+
a) Expression evaluation and syntax parsing
37+
b) Finding the correct path in maze using back tracking
38+
c) Runtime memory management
39+
d) Recursion function
40+
41+
6. Queue
42+
- Data structure which stores the data in FIFO form i.e FIRST IN FIRST OUT. Think of a queue outside movie theatre. Can be used in below cases,
43+
a) When order is needed
44+
b) When processing is needed in FIFO order
45+
c) If we want to add or remove, both ends, queue can be used or double ended queue
46+
47+
7. Binary Tree
48+
- A tree data structure where each node has atmost 2 childs. Can be used in below cases,
49+
a) Find name in the phone book
50+
b) Sorted traversal of the tree
51+
c) Find the next closest element
52+
d) Find all elements less then or greater then certain value
53+
54+
8. Binary Search Tree (BST)
55+
- A tree data strucutre, in which root node is equal to or greater then the root node of left subtree and less then or equal to root node of right sub tree.
56+
a) They are memory efficient
57+
b) To be used when data needs to be sorted
58+
c) Search can be done on range of values
59+
d) Height balancing helps in reducing the run time
60+
61+
62+
9. B Tree
63+
- B-tree is a tree data structure that keeps data sorted and allows searches, sequential access, insertions, and deletions in logarithmic time. The developer can use B-Tree in the following use cases.
64+
a) File systems.
65+
b) Database operations.
66+
67+
10. Red Black Tree
68+
- Red–black tree is a binary search tree with an extra bit of data per node, its color, which can be either red or black. The developer can use Red-Black Tree in the following use cases.
69+
a) Java Tree Map and C++ map implemented using Red Block Tree.
70+
b)Computational Geometry Data structures.
71+
c) Scheduler applications.
72+
73+
11. Splay Tree
74+
- A splay tree is a self-adjusting binary search tree with the additional property that recently accessed elements are quick to access again. The developer can use Splay Tree in the following use cases.
75+
a) When the developer wants access the recent data easily.
76+
b) Allow duplicate items.
77+
c) Simple implementation and take less memory.
78+
d) When the application deals with a lot of data, use the splay tree.
79+
80+
12. AVL Tree
81+
- AVL tree, the shape of the tree is constrained at all times such that the tree shape is balanced. The height of the tree never exceeds O(log n). The developer can use AVL Tree in the following use cases.
82+
a) When the developer wants to control the tree height outside -1 to 1 range.
83+
b) Fast looking element.
84+
85+
13. Minimum Spanning Tree
86+
- A spanning tree of that graph is a subgraph that is a tree and connects all the vertices together. A minimum spanning tree (MST) or minimum weight spanning tree is then a spanning tree with weight less than or equal to the weight of every other spanning tree. The developer can use Minimum Spanning Tree in the following use cases.
87+
a) Describe financial markets.
88+
b) Handwriting recognition of mathematical expressions.
89+
c) Image registration and segmentation.
90+
d) Constructing trees for broadcasting in computer networks.
91+
92+
14. Trie
93+
- A Trie (digital tree and sometimes radix tree or prefix tree), is an ordered tree data structure that is used to store a dynamic set or associative array where the keys are usually strings. The developer can use Trie in the following use cases.
94+
a) Fixed dictionary and want to look up quickly.
95+
b) Require less storage for a large dictionary.
96+
c) Matching sentences during string matching.
97+
d) Predictable O(k) lookup time where k is the size of the key.
98+
e) Lookup can take less than k time if it’s not there.
99+
f) Supports ordered traversal.
100+
g) No need for a hash function.
101+
h) Deletion is straightforward.
102+
103+
15. Heap
104+
- A heap is a specialized tree-based abstract data type that satisfies the heap property. The developer can use Heap in the following use cases.
105+
a) Implement Priority Queue.
106+
b) whenever the developer want quick access to the largest (or smallest) item.
107+
c) Good for selection algorithms (finding the min or max).
108+
d) Operations tend to be faster than for a binary tree.
109+
e) Heap sort sorting methods being in-place and with no quadratic worst-case scenarios.
110+
f) Graph algorithms are using heaps as internal traversal data structures, run time will be reduced by polynomial order.
111+
112+
16. Hashing
113+
- Hash table is a data structure used to implement an associative array, a structure that can map keys to values. The developer can use Hash table in the following use cases.
114+
a) Constant time operation.
115+
b) Inserts are generally slow, reads are faster than trees.
116+
c) Hashing is used so that searching a database can be done more efficiently.
117+
d) Internet routers use hash tables to route the data from one computer to another.
118+
e) Internet search engine uses hash function effectively.
119+
120+
17. Graph
121+
- The graph is an abstract data type that is meant to implement the graph and directed graph concepts from mathematics. The developer can use Graph in the following use cases.
122+
a) Networks have many uses in the practical side of graph theory.
123+
b) Finding the shortest path between the cities.
124+
c) Solve maze game.
125+
d) Find the optimized route between the cities.
126+
127+
18. Matrix
128+
- Matrix is a data structure which store the data using rows and columns. The developer can use Matrix in the following use cases.
129+
a) Matrix arithmetic in graphic processing algorithms.
130+
b) Represent the graph.
131+
c) Represent quadratic forms and linear algebra solution.
132+

0 commit comments

Comments
 (0)