Skip to content

Commit cdc5409

Browse files
committed
Add implementation of BST tree
1 parent b0a12e5 commit cdc5409

File tree

12 files changed

+323
-36
lines changed

12 files changed

+323
-36
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ List of Programs related to data structures and algorithms
136136

137137
### Tree
138138

139-
1. Maximum depth of binary tree: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/tree/maxDepthBinaryTree.js)
139+
1. Maximum depth of binary tree: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/tree/1.maxDepthBinaryTree/maxDepthBinaryTree.js)
140140

141141
2. Same tree: [JavaScript](https://livecodes.io/?console&x=https://github.com/sudheerj/datastructures-algorithms/blob/master/src/javascript/algorithms/tree/sameTree.js)
142142

src/images/bfs-traversal.png

42.3 KB
Loading

src/images/bst.png

35.6 KB
Loading

src/images/dfs-inorder.png

45.1 KB
Loading

src/images/dfs-postorder.png

44.5 KB
Loading

src/images/dfs-preorder.png

54.2 KB
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
package java1.datastructures.tree.binarytree;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.LinkedList;
6+
import java.util.List;
7+
import java.util.Queue;
8+
9+
class Node {
10+
public Node left;
11+
public Node right;
12+
public int value;
13+
14+
Node(int value){
15+
this.value = value;
16+
this.left = null;
17+
this.right = null;
18+
}
19+
}
20+
public class BinarySearchTree {
21+
22+
private Node root;
23+
24+
BinarySearchTree(){
25+
this.root = null;
26+
}
27+
28+
public void insert(int value){
29+
Node newNode = new Node(value);
30+
if(this.root == null) {
31+
this.root = newNode;
32+
return;
33+
}
34+
35+
Node currentNode = this.root;
36+
while (true) {
37+
if(value < currentNode.value) {
38+
if(currentNode.left == null) {
39+
currentNode.left = newNode;
40+
return;
41+
}
42+
currentNode = currentNode.left;
43+
44+
} else if(value > currentNode.value) {
45+
if(currentNode.right == null) {
46+
currentNode.right = newNode;
47+
return;
48+
}
49+
currentNode = currentNode.right;
50+
} else {
51+
return;
52+
}
53+
}
54+
}
55+
56+
public boolean lookup(int value){
57+
if(this.root == null) return false;
58+
59+
Node currentNode = this.root;
60+
61+
while (currentNode != null) {
62+
if(value < currentNode.value) {
63+
currentNode = currentNode.left;
64+
} else if(value > currentNode.value) {
65+
currentNode = currentNode.right;
66+
} else {
67+
return true;
68+
}
69+
}
70+
71+
return false;
72+
}
73+
74+
public Node minValueNode(Node current){
75+
while(true){
76+
if(current.left == null) return current;
77+
current = current.left;
78+
}
79+
}
80+
81+
public Node maxValueNode(Node current){
82+
while(true){
83+
if(current.right == null) return current;
84+
current = current.right;
85+
}
86+
}
87+
88+
public void bfs(){
89+
Node currentNode = this.root;
90+
List<Integer> output = new ArrayList<>();
91+
Queue<Node> queue = new LinkedList<>();
92+
queue.add(currentNode);
93+
94+
while (queue.size() != 0) {
95+
currentNode = queue.remove();
96+
output.add(currentNode.value);
97+
if(currentNode.left != null) queue.add(currentNode.left);
98+
if(currentNode.right != null) queue.add(currentNode.right);
99+
}
100+
101+
System.out.println(Arrays.deepToString(output.toArray()));
102+
}
103+
104+
public void dfsPreOrder(){
105+
List<Integer> output = new ArrayList<>();
106+
107+
class Traversal {
108+
Traversal(Node currentNode){
109+
output.add(currentNode.value);
110+
if(currentNode.left != null) new Traversal(currentNode.left);
111+
if(currentNode.right != null) new Traversal(currentNode.right);
112+
}
113+
}
114+
115+
new Traversal(root);
116+
System.out.println(Arrays.deepToString(output.toArray()));
117+
}
118+
119+
public void dfsPostOrder(){
120+
List<Integer> output = new ArrayList<>();
121+
122+
class Traversal {
123+
Traversal(Node currentNode) {
124+
if(currentNode.left != null) new Traversal(currentNode.left);
125+
if(currentNode.right != null) new Traversal(currentNode.right);
126+
output.add(currentNode.value);
127+
}
128+
}
129+
130+
new Traversal(root);
131+
System.out.println(Arrays.deepToString(output.toArray()));
132+
}
133+
134+
public void dfsInOrder(){
135+
List<Integer> output = new ArrayList<>();
136+
137+
class Traversal {
138+
Traversal(Node currentNode) {
139+
if(currentNode.left != null) new Traversal(currentNode.left);
140+
output.add(currentNode.value);
141+
if(currentNode.right != null) new Traversal(currentNode.right);
142+
}
143+
}
144+
145+
new Traversal(root);
146+
System.out.println(Arrays.deepToString(output.toArray()));
147+
}
148+
149+
public static void main(String[] args) {
150+
BinarySearchTree tree = new BinarySearchTree();
151+
tree.insert(20);
152+
tree.insert(15);
153+
tree.insert(25);
154+
tree.insert(12);
155+
tree.insert(16);
156+
tree.insert(22);
157+
tree.insert(30);
158+
tree.insert(10);
159+
tree.insert(14);
160+
tree.insert(28);
161+
tree.insert(35);
162+
163+
System.out.println(tree.lookup(25));
164+
System.out.println(tree.lookup(7));
165+
System.out.println(tree.lookup(10));
166+
System.out.println(tree.lookup(12));
167+
System.out.println(tree.minValueNode(tree.root.left).value);
168+
System.out.println(tree.maxValueNode(tree.root.right).value);
169+
170+
tree.bfs();
171+
tree.dfsPreOrder();
172+
tree.dfsPostOrder();
173+
tree.dfsInOrder();
174+
}
175+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
A Binary Search Tree (BST) is a binary tree where every node in the left subtree is less than the root, and every node in the right subtree is of a value greater than the root. This datastructure is mainly used for operations like search, delete, and insert. These operations are fast and efficient without shifting values in memory.
2+
3+
**Note:** Each left and right subtrees must also be Binary Search Tree.
4+
5+
### Types of BSTs:
6+
7+
1. **Full Binary Search Tree:** Each node will have either 0 or 2 children
8+
2. **Complete Binary Search Tree:** All the levels of the tree are filled completely except possibly the lowest level nodes which are filled from the left.
9+
3. **Perfect Binary Search Tree:** It is both full and complete BST. In which, all the leaf nodes are at the same depth, and all non-leaf nodes have two children.
10+
11+
The structure of binary search tree looks like below,
12+
13+
![Screenshot](../../../images/bst.png)
14+
15+
The tree can have the following functionalities,
16+
17+
1. **Insert:** This method is used to insert a new node inside BST based on node's value. If the root node is null, update the root node with newnode and return the tree. Otherwise, you need to traverse the tree using a loop and insert the new node based on its value. i.e, First, assign the root node as current node. If the node value is less than current node, the node needs to be inserted on left subtree. Otherwise, the new node needs to be inserted on right subtree. The iteration continues until the node is inserted or already exists.
18+
19+
2. **Lookup:** The lookup method finds a node in tree. If the root is null, just return false. Otherwise traverse the tree starting from root node. If the given value is less than current node' value, the left subtree needs to traversed. If not, the right subtree needs to be traversed to find the value. In case, the value is equal to particular node value, return true to indicate that the value exists.
20+
21+
3. **Min value node**: The minimum value of a particular tree is identified on left subtree. If the left node doesn't exists, the current value will become the minimum value node.
22+
23+
4. **Max value node**: The maximum value of a particular tree is identified on right subtree. If the right node doesn't exists, the current value will become the maximum value node.
24+
25+
5. **BFS traversal:** BSF begins with a particular node, and then first traverses all its adjacent. Once all adjacent are visited, then their adjacent are traversed. i.e, It visits the nodes level by level.
26+
27+
![Screenshot](../../../images/bfs-traversal.png)
28+
29+
The BFS traversal is implemented in the below step by step manner.
30+
31+
1. Initially, the current node(`current`) is set to the root of the binary tree to indicate the starting point of the traversal.
32+
33+
2. An empty array `output` is initialized to store the node values in the order they are visited.
34+
35+
3. An empty array `queue` is initialized to perform the breadth-first traversal of the tree. The root node is added to the queue.
36+
37+
4. Iterate using a while loop until there are nodes in the queue. For each iteration,
38+
39+
1. Remove the first node from the queue and assign it to `currentNode`.
40+
2. Add the currentNode value to the `output` array.
41+
3. If the currentNode has a left child, add it to the queue.
42+
4. If the currentNode has a right child, add it to the queue.
43+
44+
5. Once the while loop is completed, all nodes in the binary tree have been visited. Return `output` array containing the node values in breadth-first order.
45+
46+
6. **DFS traversal:** It begins at the root node and then it explores each branch before backtracking. This is implemented using stacks and recursion stacks helpful to backtrack.
47+
48+
i. **PreOrder** In pre-order traversal of a binary tree, first traverse the root node, then the left subtree and then finally the right subtree.
49+
50+
![Screenshot](../../../images/dfs-preorder.png)
51+
52+
ii. **PostOrder** In post-order traversal of a binary tree, first traverses the left subtree, then the right subtree and then finally the root node.
53+
54+
![Screenshot](../../../images/dfs-postorder.png)
55+
56+
iii. **InOrder** In-order traversal of a binary tree, first traverses the left subtree, then the root node and finally the right subtree.
57+
58+
![Screenshot](../../../images/dfs-inorder.png)

src/javascript/algorithms/tree/1.maxDepthBinaryTree/maxDepthBinaryTree.md

Whitespace-only changes.

src/javascript/datastructures/trees/binary_search_tree.js

+31-35
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ class BinarySearchTree {
2626
return this;
2727
}
2828
currentNode = currentNode.left
29-
} else if (value > currentNode.right){
29+
} else if (value > currentNode.value){
3030
// Right
3131
if(currentNode.right === null) {
3232
currentNode.right = newNode;
@@ -38,34 +38,22 @@ class BinarySearchTree {
3838
}
3939
}
4040
}
41+
4142
lookup(value) {
4243
if(this.root === null) {
4344
return false;
4445
}
4546
let currentNode = this.root;
46-
while(true) {
47-
if(value < currentNode.left) {
47+
while(currentNode) {
48+
if(value < currentNode.value) {
4849
currentNode = currentNode.left;
49-
} else if(value > currentNode.right) {
50+
} else if(value > currentNode.value) {
5051
currentNode = currentNode.right;
5152
} else {
5253
return true;
5354
}
5455
}
55-
}
5656

57-
contains(value) {
58-
if (this.root === null) return false;
59-
let temp = this.root;
60-
while (temp) {
61-
if (value < temp.value) {
62-
temp = temp.left;
63-
} else if (value > temp.value) {
64-
temp = temp.right;
65-
} else {
66-
return true;
67-
}
68-
}
6957
return false;
7058
}
7159

@@ -83,7 +71,7 @@ class BinarySearchTree {
8371
}
8472
}
8573

86-
BFS() {
74+
bfs() {
8775
let currentNode = this.root;
8876
let queue = [];
8977
let output = [];
@@ -98,7 +86,7 @@ class BinarySearchTree {
9886
return output;
9987
}
10088

101-
DFSPreOrder() {
89+
dfsPreOrder() {
10290
let output = [];
10391
function traverse(currentNode) {
10492
output.push(currentNode.value);
@@ -109,7 +97,7 @@ class BinarySearchTree {
10997
return output;
11098
}
11199

112-
DFSPostOrder() {
100+
dfsPostOrder() {
113101
let output = [];
114102
function traverse(currentNode) {
115103
if(currentNode.left) traverse(currentNode.left);
@@ -120,7 +108,7 @@ class BinarySearchTree {
120108
return output;
121109
}
122110

123-
DFSInOrder() {
111+
dfsInOrder() {
124112
let output = [];
125113
function traverse(currentNode) {
126114
if(currentNode.left) traverse(currentNode.left);
@@ -133,19 +121,27 @@ class BinarySearchTree {
133121
}
134122

135123
const tree = new BinarySearchTree();
136-
tree.insert(80);
137-
tree.insert(100);
138-
tree.insert(50);
139-
console.log(tree.lookup(50));
140-
tree.insert(90);
141-
console.log(tree.lookup(88));
142-
console.log(tree.contains(100));
143-
console.log(tree.contains(9));
124+
tree.insert(20);
125+
tree.insert(15);
126+
tree.insert(25);
127+
tree.insert(12);
128+
tree.insert(16);
129+
tree.insert(22);
130+
tree.insert(30);
131+
tree.insert(10);
132+
tree.insert(14);
133+
tree.insert(28);
134+
tree.insert(35);
135+
console.dir(tree, {depth: null});
136+
137+
console.log(tree.lookup(25));
138+
console.log(tree.lookup(7));
139+
console.log(tree.lookup(10));
140+
console.log(tree.lookup(12));
144141
console.log(tree.minValueNode(tree.root.left));
145142
console.log(tree.maxValueNode(tree.root.right));
146-
tree.insert(12);
147-
tree.insert(67);
148-
console.log(tree.BFS());
149-
console.log(tree.DFSPreOrder());
150-
console.log(tree.DFSPostOrder());
151-
console.log(tree.DFSInOrder());
143+
144+
console.log(tree.bfs());
145+
console.log(tree.dfsPreOrder());
146+
console.log(tree.dfsPostOrder());
147+
console.log(tree.dfsInOrder());

0 commit comments

Comments
 (0)