Skip to content

Commit 5bacaaf

Browse files
authored
Trees presentation (Binary tree and BTS)
0 parents  commit 5bacaaf

File tree

5 files changed

+364
-0
lines changed

5 files changed

+364
-0
lines changed

Diff for: Dsa.js

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// Problem Statement:
2+
// Given a binary tree, find the
3+
//maximum depth (height) of the tree.
4+
//The maximum depth of a binary tree is the
5+
// length of the longest path from the root node to any leaf node
6+
class TreeNode {
7+
constructor(value) {
8+
this.value = value;
9+
this.left = null;
10+
this.right = null;
11+
}
12+
}
13+
14+
//javascript implementation
15+
// Helper function to create a binary tree for demonstration purposes
16+
function createBinaryTree() {
17+
const root = new TreeNode(1);
18+
root.left = new TreeNode(2);
19+
root.right = new TreeNode(3);
20+
root.left.left = new TreeNode(4);
21+
root.left.right = new TreeNode(5);
22+
root.right.left = new TreeNode(6);
23+
root.right.right = new TreeNode(7);
24+
return root;
25+
}
26+
27+
28+
//algorithm implementation
29+
// Function to find the maximum depth (height) of a binary tree using recursion
30+
function maxDepth(root) {
31+
if (!root) {
32+
return 0;
33+
} else {
34+
const leftDepth = maxDepth(root.left);
35+
// console.log(leftDepth)
36+
console.log("leftpath:", leftDepth);
37+
const rightDepth = maxDepth(root.right);
38+
// console.log(rightDepth)
39+
return 1 + Math.max(leftDepth, rightDepth);
40+
}
41+
}
42+
43+
// Example usage:
44+
const root = createBinaryTree();
45+
const depth = maxDepth(root);
46+
console.log("Maximum Depth of Binary Tree:", depth); // Output: Maximum Depth of Binary Tree: 3
47+
48+
// Explanation:
49+
// In this example, we define a simple binary tree using the TreeNode class. Then, we create a binary tree using the createBinaryTree function. After that, we implement the maxDepth function using recursion to find the maximum depth of the binary tree. The function starts with the root node and recursively calculates the maximum depth of its left and right subtrees. The maximum depth of the binary tree is the maximum value between the depth of the left subtree and the depth of the right subtree, plus 1 to account for the current level.
50+
51+
// In this case, the binary tree has a maximum depth of 3, and the function correctly computes and returns this value.
52+
53+
54+
55+
56+
57+
// Regenerate

Diff for: README.md

+95
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
# WHAT ARE TREESS
2+
A tree is a **hierarchical data structure** consisting of nodes connected by edges
3+
4+
- Each node in a tree has a parent node (except for the root node) and zero or more child nodes. The topmost node in a tree is called the "root," and nodes with no children are called "leaves."
5+
6+
[image visualization of a tree structure](https://media.geeksforgeeks.org/wp-content/uploads/20221124153129/Treedatastructure.png)
7+
8+
### Most commonly used Types of Trees
9+
- Binary Tree: A binary tree is a tree data structure where each node has at most two children, referred to as the left child and the right child. Binary trees are commonly used in various algorithms like binary search, binary tree traversals, and binary heap implementations.
10+
11+
- Binary Search Tree (BST): A binary search tree is a binary tree where each node's left child has a value less than the node, and the right child has a value greater than the node. This property makes searching, insertion, and deletion operations efficient
12+
- Trie (Prefix Tree): A trie is a tree-like data structure used for efficiently storing and searching strings. It is particularly useful for tasks like autocomplete, spell-checking, and searching for words with common prefixes
13+
14+
- N-ary Tree: An N-ary tree is a tree data structure where each node can have more than two children. In contrast to binary trees, N-ary trees allow a variable number of child nodes per parent node
15+
16+
- Heap: Although a heap is not a strict tree data structure, it can be represented as a binary tree. A heap is a specialized tree-based data structure that satisfies the heap property, making it efficient for finding the maximum or minimum element in constant time and for efficiently extracting the extremum element
17+
18+
others
19+
- AVL Tree
20+
- Red-Black Tree
21+
- Segment Tree
22+
***
23+
24+
### Terminologies
25+
- Degree - The degree of a node is the total number of children it has
26+
- Depth - Depth of a node is the number of edges from the root to that node (depth of root node is always zero)
27+
28+
- Height - The numbe of edges form the deepest leaf to that node (height of the root node is considered to be the height of the tree)
29+
30+
31+
***
32+
- a tree is a non linear data structure compared to arrays, linked lists, stacks and queues which are linear data structures( elements are arranged in a sequential order, and each element has a unique predecessor (except for the first element) and a unique successor (except for the last element) ).
33+
34+
- non linear - means elements can have multiple predecessors or successors, leading to more complex relationships between elements
35+
36+
### Advantages of using non linear data structures e.g trees
37+
1. Flexible Relationships: Non-linear data structures enable multiple relationships between elements. In graphs, nodes can have any number of connections (edges) to other nodes, allowing for more complex and diverse data relationships
38+
2. Complex Algorithms: Many advanced algorithms, such as graph algorithms (e.g., Dijkstra's algorithm, breadth-first search, depth-first search), rely on non-linear data structures to solve complex problems efficiently. These algorithms find applications in route planning, network analysis, social networks, and more
39+
3. Dynamic Data: Non-linear data structures can handle dynamic data well, as they allow easy insertion and deletion of elements without much disruption to the overall structure
40+
4. Hierarchical Representation: Non-linear data structures like trees allow for hierarchical representation, which can model real-world relationships more accurately. For example, an organization's hierarchy, file systems, and family trees can be represented more naturally using trees
41+
42+
5. Efficient Data Retrieval: Depending on the specific non-linear data structure and the use case, retrieval of specific data elements can be more efficient compared to linear data structures. For instance, in balanced binary search trees, searching for an element takes O(log n) time, which is faster than linear search in an array (O(n)) ... time required to search is propotinal to the size of the data set...
43+
44+
45+
### Operations u can use in a BST
46+
- insertion
47+
- Search
48+
- DFS - Depth-First Search - it is a traversal algorithm used to visit all the nodes in a tree or graph data structure
49+
- BFS - Breadth-First Search - it is a traversal algorithm used to visit all the nodes in a tree or graph data structure level by level.
50+
- Deletion - remove a node given its value
51+
52+
53+
54+
### Trees implementation in software/programs
55+
56+
- Trees are widely used in computer science and programming due to their versatility and efficiency in organizing and representing data in a hierarchical manner.
57+
e.g
58+
1. representing file systems - File systems often use BSTs to organize and search for files and directories efficiently.
59+
2. organizing hierarchical data like organizational charts, DOM (NOT A TREEE BUT tree-like structure to represent the hierarchical relationships among HTML elements in a web page, **each HTML element e.g., div, h1, etc.) is a node in the tree,**
60+
3. implementing search algorithms like binary search trees(most popular implementation)
61+
4. Sorting
62+
5. auto predictions in keyboards e.g Search Autocomplete: Trie (a type of tree) can be used to implement an efficient search autocomplete feature, suggesting products or categories as the user types in the search bar.
63+
64+
6. Contacts List: Many contact management applications use BSTs to sort and search contacts by name.
65+
7. Spell Checkers: BSTs are used in spell checkers to efficiently check if a given word is present in the dictionary
66+
67+
68+
## How to use BTS
69+
70+
- There is no built-in method that directly uses a Binary Search Tree (BST). JavaScript provides basic data structures like arrays and objects, but it does not include native support for tree data structures.
71+
72+
- If you want to use a BST in JavaScript, you'll need to implement it yourself or use a third-party library that provides BST functionality
73+
74+
- LIBRARIES EXAMPLES INCLUDE bintrees" AND "binary-search-tree
75+
76+
`````` javascript
77+
const bintrees = require('bintrees');
78+
const { AVLTree } = bintrees;
79+
80+
// Create a new AVLTree
81+
const bst = new AVLTree((a, b) => a.key - b.key);
82+
83+
// Insert elements
84+
bst.insert({ key: 10, value: 'data1' });
85+
bst.insert({ key: 5, value: 'data2' });
86+
bst.insert({ key: 15, value: 'data3' });
87+
88+
// Search for elements
89+
const node = bst.find({ key: 5 });
90+
console.log(node && node.value); // Output: 'data2'
91+
92+
93+
94+
95+

Diff for: bst.js

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// Define a Node class to represent each node in the binary search tree
2+
class Node {
3+
constructor(value) {
4+
this.value = value;
5+
this.left = null;
6+
this.right = null;
7+
}
8+
}
9+
10+
// Define the Binary Search Tree class
11+
class BinarySearchTree {
12+
constructor() {
13+
this.root = null;
14+
}
15+
16+
// Method to insert a new node into the BST
17+
insert(value) {
18+
const newNode = new Node(value);
19+
20+
if (this.root === null) {
21+
this.root = newNode;
22+
} else {
23+
this.insertNode(this.root, newNode);
24+
}
25+
}
26+
//helper function
27+
insertNode(node, newNode) {
28+
if (newNode.value < node.value) {
29+
if (node.left === null) {
30+
node.left = newNode;
31+
} else {
32+
this.insertNode(node.left, newNode);
33+
}
34+
} else {
35+
if (node.right === null) {
36+
node.right = newNode;
37+
} else {
38+
this.insertNode(node.right, newNode);
39+
}
40+
}
41+
}
42+
43+
// Method to perform binary search
44+
search(target) {
45+
return this.searchNode(this.root, target);
46+
}
47+
48+
searchNode(node, target) {
49+
if (node === null || node.value === target) {
50+
return node;
51+
}
52+
53+
if (target < node.value) {
54+
return this.searchNode(node.left, target);
55+
} else {
56+
return this.searchNode(node.right, target);
57+
}
58+
}
59+
}
60+
61+
// Example usage:
62+
const bst = new BinarySearchTree();
63+
bst.insert(5);
64+
bst.insert(3);
65+
bst.insert(8);
66+
bst.insert(1);
67+
bst.insert(4);
68+
bst.insert(7);
69+
bst.insert(9);
70+
71+
72+
const targetValue = 10;
73+
const result = bst.search(targetValue);
74+
75+
console.log(bst)
76+
if (result) {
77+
console.log(`Found ${targetValue} in the BST.`);
78+
} else {
79+
console.log(`${targetValue} not found in the BST.`);
80+
}
81+

Diff for: case.js

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// Suppose you have a text file containing a list of valid words, each word separated
2+
// by a newline character. We can construct a BST with these words where each node
3+
// contains a word, and its left child node contains words that come before it in
4+
// alphabetical order, while the right child node contains words that come after it.
5+
6+
class Node {
7+
constructor(value) {
8+
this.value = value;
9+
this.left = null;
10+
this.right = null;
11+
}
12+
}
13+
14+
class SpellChecker {
15+
constructor() {
16+
this.root = null;
17+
}
18+
19+
insert(word) {
20+
if (!this.root) {
21+
this.root = new Node(word);
22+
} else {
23+
this._insertNode(this.root, word);
24+
}
25+
}
26+
///helper function
27+
_insertNode(node, word) {
28+
if (word < node.value) {
29+
if (node.left) {
30+
this._insertNode(node.left, word);
31+
} else {
32+
node.left = new Node(word);
33+
}
34+
} else if (word > node.value) {
35+
if (node.right) {
36+
this._insertNode(node.right, word);
37+
} else {
38+
node.right = new Node(word);
39+
}
40+
}
41+
}
42+
43+
search(word) {
44+
return this._searchNode(this.root, word);
45+
}
46+
47+
_searchNode(node, word) {
48+
if (!node) {
49+
return false;
50+
}
51+
52+
if (word === node.value) {
53+
return true;
54+
} else if (word < node.value) {
55+
return this._searchNode(node.left, word);
56+
} else {
57+
return this._searchNode(node.right, word);
58+
}
59+
}
60+
}
61+
62+
// Usage:
63+
const spellChecker = new SpellChecker();
64+
const validWords = ["apple", "banana", "orange", "grape", "pear"];
65+
66+
// Construct the BST
67+
validWords.forEach((word) => {
68+
spellChecker.insert(word);
69+
});
70+
71+
72+
console.log(spellChecker)
73+
// Search for a word
74+
const searchWord = "banana";
75+
if (spellChecker.search(searchWord)) {
76+
console.log(`${searchWord} is a valid word.`);
77+
} else {
78+
console.log(`${searchWord} is not a valid word.`);
79+
}

Diff for: trees.js

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// console.log("this should work")
2+
// Define a Node class to represent each member of the family
3+
4+
class Node {
5+
constructor(name){
6+
this.name = name;
7+
this.children = [];
8+
}
9+
10+
//add children function
11+
addChildren(Childname){
12+
this.children.push(Childname)
13+
}
14+
// Create the family tree
15+
16+
17+
}
18+
19+
const familyTree = new Node("Grandpa");
20+
const dad = new Node("Dad");
21+
const mom = new Node("Mom");
22+
familyTree.addChildren(dad);
23+
// familyTree.addChildren(mom);
24+
const child1 = new Node("Judy");
25+
const child2 = new Node("James");
26+
const child3 = new Node("Joyce");
27+
dad.addChildren(child1);
28+
// dad.addChildren(child2);
29+
// mom.addChildren(child3);
30+
31+
console.log(familyTree.children[0].children[0].name)
32+
// Function to print the family tree recursively
33+
function printFamilyTree(node, level = 0) {
34+
const indentation = " ".repeat(level); // Add spaces for indentation
35+
36+
// console.log(`${indentation}- ${node.name}`);
37+
38+
for (const child of node.children) {
39+
printFamilyTree(child, level + 1);
40+
}
41+
}
42+
43+
// // Print the family tree
44+
// console.log("Family Tree:");
45+
// printFamilyTree(familyTree);
46+
47+
// console.log(familyTree)
48+
49+
50+
51+
52+

0 commit comments

Comments
 (0)