filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/data_structures/src/tree/binary_tree/binary_tree/minimum_height/README.md
# Cosmos Collaborative effort by [OpenGenus](https://github.com/OpenGenus/cosmos)
code/data_structures/src/tree/binary_tree/binary_tree/minimum_height/minimum_height.c
#include <stdio.h> #include <stdlib.h> // Part of Cosmos by OpenGenus Foundation typedef struct node { int value; struct node *left, *right; }node; static node* root = NULL; node* create_node(int val) { node* tmp = (node *) malloc(sizeof(node)); tmp->value = val; tmp->left = tmp->right = NULL; return tmp; } void create_tree(int val) { node* tmp = root; if (!root) root = create_node(val); else { while (1) { if (val > tmp->value) { if (!tmp->right) { tmp->right = create_node(val); break; } else tmp = tmp->right; } else { if (!tmp->left) { tmp->left= create_node(val); break; } else tmp = tmp->left; } } } } int min(int left_ht, int right_ht) { return (left_ht < right_ht ? left_ht : right_ht); } int min_depth_tree(node* tmp) { if (!tmp) return 0; if (!tmp->left && !tmp->right) return 1; if (!tmp->left) return min_depth_tree(tmp->right)+1; if (!tmp->right) return min_depth_tree(tmp->left)+1; return min(min_depth_tree(tmp->left),min_depth_tree(tmp->right))+1; } int main() { int ctr, num_nodes, value,min_depth; printf("Enter number of nodes\n"); scanf("%d",&num_nodes); for (ctr = 0; ctr < num_nodes; ctr++) { printf("Enter values\n"); scanf("%d",&value); create_tree(value); } min_depth = min_depth_tree(root); printf("minimum depth = %d\n",min_depth); }
code/data_structures/src/tree/binary_tree/binary_tree/minimum_height/minimum_height.cpp
#include <iostream> using namespace std; typedef struct tree_node { int value; struct tree_node *left, *right; }node; // create a new node node *getNewNode(int value) { node *new_node = new node; new_node->value = value; new_node->left = NULL; new_node->right = NULL; return new_node; } // create the tree node *createTree() { node *root = getNewNode(31); root->left = getNewNode(16); root->right = getNewNode(45); root->left->left = getNewNode(7); root->left->right = getNewNode(24); root->left->right->left = getNewNode(19); root->left->right->right = getNewNode(29); return root; } int minDepth(node* A) { if (A == NULL) return 0; int l = minDepth(A->left); int r = minDepth(A->right); if (l && r) return min(l, r) + 1; if (l) return l + 1; return r + 1; } // main int main() { node *root = createTree(); cout << minDepth(root); cout << endl; return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/minimum_height/minimum_height.java
class TreeNode<T> { T data; TreeNode<T> left,right; public TreeNode(T data) { this.data = data; } } public class BinaryTree { public static <T> int minHeight(TreeNode<T> root) { if(root == null) return 0; return Math.min(minHeight(root.left), minHeight(root.right)) + 1; } public static void main(String[] args) { TreeNode<Integer> root = new TreeNode<Integer>(1); root.left = new TreeNode<Integer>(2); root.right = new TreeNode<Integer>(3); root.left.left = new TreeNode<Integer>(4); root.left.right = new TreeNode<Integer>(5); root.right.left = new TreeNode<Integer>(6); System.out.println(minHeight(root)); } }
code/data_structures/src/tree/binary_tree/binary_tree/minimum_height/minimum_height.py
# Python program to find minimum depth of a given Binary Tree # Part of Cosmos by OpenGenus Foundation # Tree node class Node: def __init__(self, key): self.data = key self.left = None self.right = None def minDepth(root): # Corner Case.Should never be hit unless the code is # called on root = NULL if root is None: return 0 # Base Case : Leaf node.This acoounts for height = 1 if root.left is None and root.right is None: return 1 # If left subtree is Null, recur for right subtree if root.left is None: return minDepth(root.right) + 1 # If right subtree is Null , recur for left subtree if root.right is None: return minDepth(root.left) + 1 return min(minDepth(root.left), minDepth(root.right)) + 1 # Driver Program root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print(minDepth(root))
code/data_structures/src/tree/binary_tree/binary_tree/node/node.cpp
/* * Part of Cosmos by OpenGenus Foundation * * tree node synopsis * * // for normal binary tree * template<typename _Type> * class TreeNode * { * protected: * using SPNodeType = std::shared_ptr<TreeNode>; * using ValueType = _Type; * * public: * TreeNode(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr) * :value_(v), left_(l), right_(r) {} * * ValueType value() { * return value_; * } * * void value(ValueType v) { * value_ = v; * } * * SPNodeType left() { * return left_; * } * * void left(SPNodeType l) { * left_ = l; * } * * SPNodeType right() { * return right_; * } * * void right(SPNodeType r) { * right_ = r; * } * * private: * ValueType value_; * SPNodeType left_; * SPNodeType right_; * }; * * // for derivative binary tree (e.g., avl tree, splay tree) * template<typename _Type, class _Derivative> * class __BaseTreeNode * { * protected: * using SPNodeType = std::shared_ptr<_Derivative>; * using ValueType = _Type; * * public: * __BaseTreeNode(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr) * :value_(v), left_(l), right_(r) {} * * ValueType value() { * return value_; * } * * void value(ValueType v) { * value_ = v; * } * * SPNodeType left() { * return left_; * } * * void left(SPNodeType l) { * left_ = l; * } * * SPNodeType right() { * return right_; * } * * void right(SPNodeType r) { * right_ = r; * } * * private: * ValueType value_; * SPNodeType left_; * SPNodeType right_; * }; * * template<typename _Type> * class DerivativeTreeNode :public __BaseTreeNode<_Type, DerivativeTreeNode<_Type>> * { * private: * using BaseNode = __BaseTreeNode<_Type, DerivativeTreeNode<_Type>>; * using SPNodeType = typename BaseNode::SPNodeType; * using ValueType = typename BaseNode::ValueType; * * public: * DerivativeTreeNode(_Type v, SPNodeType l = nullptr, SPNodeType r = nullptr) * :__BaseTreeNode<_Type, DerivativeTreeNode<_Type>>(v, l, r) {} * }; */ #include <memory> #ifndef TREE_NODE_POLICY #define TREE_NODE_POLICY template<typename _Type> class TreeNode { protected: using SPNodeType = std::shared_ptr<TreeNode>; using ValueType = _Type; public: TreeNode(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr) : value_(v), left_(l), right_(r) { } ValueType value() { return value_; } void value(ValueType v) { value_ = v; } SPNodeType left() { return left_; } void left(SPNodeType l) { left_ = l; } SPNodeType right() { return right_; } void right(SPNodeType r) { right_ = r; } private: ValueType value_; SPNodeType left_; SPNodeType right_; }; template<typename _Type, class _Derivative> class __BaseTreeNode { protected: using SPNodeType = std::shared_ptr<_Derivative>; using ValueType = _Type; public: __BaseTreeNode(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr) : value_(v), left_(l), right_(r) { } ValueType value() { return value_; } void value(ValueType v) { value_ = v; } SPNodeType left() { return left_; } void left(SPNodeType l) { left_ = l; } SPNodeType right() { return right_; } void right(SPNodeType r) { right_ = r; } private: ValueType value_; SPNodeType left_; SPNodeType right_; }; template<typename _Type> class DerivativeTreeNode : public __BaseTreeNode<_Type, DerivativeTreeNode<_Type>> { private: using BaseNode = __BaseTreeNode<_Type, DerivativeTreeNode<_Type>>; using SPNodeType = typename BaseNode::SPNodeType; using ValueType = typename BaseNode::ValueType; public: DerivativeTreeNode(_Type v, SPNodeType l = nullptr, SPNodeType r = nullptr) : __BaseTreeNode<_Type, DerivativeTreeNode<_Type>>(v, l, r) { } }; #endif // TREE_NODE_POLICY
code/data_structures/src/tree/binary_tree/binary_tree/path_sum/path_sum.cpp
/* * Part of Cosmos by OpenGenus Foundation */ #ifndef path_sum_cpp #define path_sum_cpp #include "path_sum.hpp" #include <queue> #include <stack> #include <set> #include <vector> #include <memory> #include <algorithm> #include <utility> #include <functional> // public template<typename _Ty, typename _Compare, class _TreeNode> auto PathSum<_Ty, _Compare, _TreeNode>::countPathsOfSum(PNode<_Ty> root, _Ty sum)->size_type { if (path_type_ == PathType::Whole) return getPathsOfSum(root, sum).size(); else // path_type_ == PathType::Part { if (root == nullptr) { return {}; } return getPathsOfSum(root, sum).size() + countPathsOfSum(root->left(), sum) + countPathsOfSum(root->right(), sum); } } template<typename _Ty, typename _Compare, class _TreeNode> std::vector<std::vector<_Ty>> PathSum<_Ty, _Compare, _TreeNode>::getPathsOfSum(PNode<_Ty> root, _Ty sum) { std::vector<std::vector<_Ty>> res{}; getPathsOfSumUp(root, {}, {}, sum, res); return res; } // public end // private template<typename _Ty, typename _Compare, class _TreeNode> void PathSum<_Ty, _Compare, _TreeNode>::getPathsOfSumUp(PNode<_Ty> root, std::vector<_Ty> prev, _Ty prev_sum, _Ty const &sum, std::vector<std::vector<_Ty>> &res) { if (root != nullptr) { auto &curr = prev; curr.push_back(root->value()); auto &curr_sum = prev_sum; curr_sum += root->value(); if (path_type_ == PathType::Whole) { if (root->left() == nullptr && root->right() == nullptr && compare_(curr_sum, sum)) res.push_back(curr); } else // path_type_ == PathType::Part if (compare_(curr_sum, sum)) res.push_back(curr); getPathsOfSumUp(root->left(), curr, curr_sum, sum, res); getPathsOfSumUp(root->right(), curr, curr_sum, sum, res); } } // private end #endif /* path_sum_cpp */
code/data_structures/src/tree/binary_tree/binary_tree/path_sum/path_sum.hpp
/* Part of Cosmos by OpenGenus Foundation */ #ifndef path_sum_hpp #define path_sum_hpp #include <memory> #include <vector> #include <functional> #include "../node/node.cpp" template<typename _Ty, typename _Compare = std::equal_to<_Ty>, class _TreeNode = TreeNode<_Ty>> class PathSum { private: template<typename _T> using Node = _TreeNode; template<typename _T> using PNode = std::shared_ptr<Node<_T>>; using size_type = size_t; public: enum class PathType { Whole, Part }; PathSum(PathType py = PathType::Whole) :compare_(_Compare()), path_type_(py) {}; ~PathSum() = default; size_type countPathsOfSum(PNode<_Ty> root, _Ty sum); std::vector<std::vector<_Ty>> getPathsOfSum(PNode<_Ty> root, _Ty sum); private: _Compare compare_; PathType path_type_; void getPathsOfSumUp(PNode<_Ty> root, std::vector<_Ty> prev, _Ty prev_sum, _Ty const &sum, std::vector<std::vector<_Ty>> &res); }; #include "path_sum.cpp" #endif /* path_sum_hpp */
code/data_structures/src/tree/binary_tree/binary_tree/path_sum/sum_left/README.md
# Cosmos Collaborative effort by [OpenGenus](https://github.com/OpenGenus/cosmos)
code/data_structures/src/tree/binary_tree/binary_tree/path_sum/sum_left/left_sum.py
# Sum of left leaves in a binary tree # Class for individual nodes class Node(object): def __init__(self, val): self.data = val self.left = None self.right = None class BinaryTree(object): def __init__(self): self.head = None def insert(self, item): if self.head == None: self.head = Node(item) else: self.add(self.head, item) def add(self, node, val): # Compare parent's value with new value if val < node.data: if node.left == None: node.left = Node(val) else: self.add(node.left, val) else: if node.right == None: node.right = Node(val) else: self.add(node.right, val) def preorder(hash_map, level, head): if head != None: if level not in hash_map.keys(): hash_map[level] = head.data preorder(hash_map, level + 1, head.left) preorder(hash_map, level + 1, head.right) if __name__ == "__main__": print("Enter number of nodes: ") num = int(input()) root = BinaryTree() for _ in range(num): print("Enter element #{}:".format(_ + 1)) item = int(input()) root.insert(item) left_elements = dict() preorder(left_elements, 0, root.head) print(sum([*left_elements.values()]))
code/data_structures/src/tree/binary_tree/binary_tree/path_sum/sum_left/sum_left.c
#include <stdio.h> #include <stdlib.h> typedef struct node { int value; int left_flag; struct node *left, *right; }node; static node* root = NULL; node* create_node(int val) { node* tmp = (node *) malloc(sizeof(node)); tmp->value = val; tmp->left_flag = 0; tmp->left = tmp->right = NULL; return tmp; } void create_tree(int val) { node* tmp = root; if (!root) root = create_node(val); else { while (1) { if (val > tmp->value) { if (!tmp->right) { tmp->right = create_node(val); break; } else tmp = tmp->right; } else { if (!tmp->left) { tmp->left= create_node(val); tmp->left->left_flag=1; break; } else tmp = tmp->left; } } } } int sum_left_leaves(node* tmp) { static int sum = 0; if(tmp) { if (!tmp->left && !tmp->right && tmp->left_flag) sum+=tmp->value; sum_left_leaves(tmp->left); sum_left_leaves(tmp->right); } return sum; } int main() { int ctr, sum, num_nodes, value,min_depth; printf("Enter number of nodes\n"); scanf("%d",&num_nodes); for (ctr = 0; ctr < num_nodes; ctr++) { printf("Enter values\n"); scanf("%d",&value); create_tree(value); } sum = sum_left_leaves(root); printf("sum = %d\n",sum); }
code/data_structures/src/tree/binary_tree/binary_tree/serializer/serializer.cpp
/* * Part of Cosmos by OpenGenus Foundation * * tree serializer synopsis * * class TreeSerializer * { * public: * using NodeType = TreeNode<int>; * using PNodeType = std::shared_ptr<NodeType>; * * // Encodes a tree to a single string. * std::string serialize(PNodeType root); * * // Decodes your encoded data to tree. * PNodeType deserialize(std::string data); * * private: * std::vector<std::string> splitToVector(std::string s); * }; */ #ifndef TREE_SERIALIZER #define TREE_SERIALIZER #include <vector> #include <stack> #include <queue> #include <iterator> #include <memory> #include <string> #include <sstream> #include "../node/node.cpp" class TreeSerializer { public: using NodeType = TreeNode<int>; using PNodeType = std::shared_ptr<NodeType>; // Encodes a tree to a single string. std::string serialize(PNodeType root) { if (root) { std::string ret {}; std::stack<PNodeType> st {}; PNodeType old {}; st.push(root); ret.append(std::to_string(root->value()) + " "); while (!st.empty()) { while (st.top() && st.top()->left()) { st.push(st.top()->left()); ret.append(std::to_string(st.top()->value()) + " "); } if (!st.top()->left()) ret.append("# "); while (!st.empty()) { old = st.top(); st.pop(); if (old->right()) { st.push(old->right()); if (st.top()) ret.append(std::to_string(st.top()->value()) + " "); break; } else ret.append("# "); } } return ret; } else return "# "; } // Decodes your encoded data to tree. PNodeType deserialize(std::string data) { if (data.at(0) == '#') return nullptr; auto nodes = splitToVector(data); std::stack<PNodeType> st{}; PNodeType ret = std::make_shared<NodeType>(stoi(nodes.at(0))), old{}; st.push(ret); size_t i{}, sz {nodes.size()}; i++; bool check_l{true}; while (!st.empty()) { while (i < sz && nodes.at(i) != "#" && check_l) { st.top()->left(std::make_shared<NodeType>(stoi(nodes.at(i++)))); st.push(st.top()->left()); } st.top()->left(nullptr); i++; check_l = false; while (!st.empty()) { old = st.top(); st.pop(); check_l = true; if (nodes.at(i) != "#") { old->right(std::make_shared<NodeType>(stoi(nodes.at(i++)))); st.push(old->right()); break; } else { old->right(nullptr); i++; } } } return ret; } private: std::vector<std::string> splitToVector(std::string s) { std::stringstream ss(s); std::istream_iterator<std::string> begin(ss); std::istream_iterator<std::string> end; std::vector<std::string> vstrings(begin, end); return vstrings; } }; #endif // TREE_SERIALIZER
code/data_structures/src/tree/binary_tree/binary_tree/traversal/inorder/right_threaded/right_threaded.cpp
/* Part of Cosmos by OpenGenus Foundation */ /* * Right-Threaded Binary Tree implementation in C++ */ //Author: Arpan Konar #include <iostream> using namespace std; typedef long long ll; #define REP(i, n) for (long long i = 0; i < (n); i++) #define FOR(i, a, b) for (long long i = (a); i <= (b); i++) #define FORD(i, a, b) for (int i = (a); i >= (b); i--) //Structure of a node struct node { int data; node * left; node * right; bool isThreaded; }; //Function to create a new node with value d node * newnode(int d) { node *temp = new node(); temp->data = d; temp->left = NULL; temp->right = NULL; temp->isThreaded = false; return temp; // the node will not be deleted } //Function to find the leftmost node of a subtree node * leftmost(node * root) { node * temp = root; while (temp != NULL && temp->left != NULL) temp = temp->left; return temp; } //Function to find a node with value b node * findNode(int b, node * root) { if (root->data == b) return root; root = leftmost(root); while (1) { if (root->data == b) return root; while (root->isThreaded) { root = root->right; if (root->data == b) return root; } if (root->right != NULL) root = leftmost(root->right); else break; } return NULL; } //Function to set the new node at left of node x node * setLeftNode(node * x, int a) { if (x->left != NULL) { cout << a << " is ignored" << endl; return x; } node * temp = newnode(a); temp->right = x; x->left = temp; temp->isThreaded = true; return x; } //Function to set the new node at right of node x node * setRightNode(node * x, int a) { if (x->right != NULL && !x->isThreaded) { cout << a << " is ignored" << endl; return x; } node * temp = newnode(a); if (x->isThreaded) { node *q = x->right; x->isThreaded = false; x->right = temp; temp->right = q; temp->isThreaded = true; } else x->right = temp; return x; } //Function to take input and create threaded tree /*Input is of the form number L/R number * where a is entered at the left or right position of b * if b is found * Input ends when a is -1 */ node * createTree() { node * root = NULL; while (1) { int a, b; char c; cin >> a; if (a == -1) break; cin >> c >> b; if (root == NULL) root = newnode(a); else { node * x = findNode(b, root); if (x == NULL) cout << "Node not found" << endl; else { if (c == 'L') x = setLeftNode(x, a); else if (c == 'R') x = setRightNode(x, a); } } } return root; } //Function for inorder traversal of threaded binary tree void inOrder(node * root) { root = leftmost(root); while (1) { cout << root->data << " "; while (root->isThreaded) { root = root->right; cout << root->data << " "; } if (root->right != NULL) root = leftmost(root->right); else break; } } //Driver function to implement the above functions int main() { node * root = createTree(); cout << "Inorder:"; inOrder(root); cout << endl; return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/traversal/preorder/left_view/left_view.java
//Java Program to print left View of a binary Tree /* Class containing left and right child of current node and key value*/ class Node { int data; Node left, right; public Node(int item) { data = item; left = right = null; } } /* Class to print the left view */ class BinaryTree { Node root; static int max_level = 0; // recursive function to print left view void leftViewUtil(Node node, int level) { // Base Case if (node==null) return; // If this is the first node of its level if (max_level < level) { System.out.print(" " + node.data); max_level = level; } // Recur for left and right subtrees leftViewUtil(node.left, level+1); leftViewUtil(node.right, level+1); } // A wrapper over leftViewUtil() void leftView() { leftViewUtil(root, 1); } /* testing for example nodes */ public static void main(String args[]) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(12); tree.root.left = new Node(10); tree.root.right = new Node(30); tree.root.right.left = new Node(25); tree.root.right.right = new Node(40); tree.leftView(); } }
code/data_structures/src/tree/binary_tree/binary_tree/traversal/preorder/right_view/README.md
# Cosmos Collaborative effort by [OpenGenus](https://github.com/OpenGenus/cosmos)
code/data_structures/src/tree/binary_tree/binary_tree/traversal/preorder/right_view/right_view.cpp
#include <iostream> using namespace std; // Part of Cosmos by OpenGenus Foundation struct node { int d; node *left; node *right; }; struct node* newnode(int num) { node *temp = new node; temp->d = num; temp->left = temp->right = NULL; return temp; } void rightview(struct node *root, int level, int *maxlevel) { if (root == NULL) return; if (*maxlevel < level) { cout << root->d << " "; *maxlevel = level; } rightview(root->right, level + 1, maxlevel); rightview(root->left, level + 1, maxlevel); } int main() { struct node *root = newnode(1); root->left = newnode(2); root->right = newnode(3); root->left->left = newnode(4); root->left->right = newnode(5); root->right->left = newnode(6); root->right->right = newnode(7); root->right->left->right = newnode(8); int maxlevel = 0; cout << "\nRight view : "; rightview(root, 1, &maxlevel); cout << endl; return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/traversal/preorder/right_view/right_view.py
# Python program to print right view of Binary Tree # Part of Cosmos by OpenGenus Foundation # A binary tree node class Node: # A constructor to create a new Binary tree Node def __init__(self, item): self.data = item self.left = None self.right = None # Recursive function to print right view of Binary Tree # used max_level as reference list ..only max_level[0] # is helpful to us def rightViewUtil(root, level, max_level): # Base Case if root is None: return # If this is the last node of its level if max_level[0] < level: print("%d " % (root.data)), max_level[0] = level # Recur for right subtree first, then left subtree rightViewUtil(root.right, level + 1, max_level) rightViewUtil(root.left, level + 1, max_level) def rightView(root): max_level = [0] rightViewUtil(root, 1, max_level) # Driver program to test above function root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) root.right.left.right = Node(8) rightView(root)
code/data_structures/src/tree/binary_tree/binary_tree/traversal/preorder/right_view/right_view2.cpp
#include <iostream> using namespace std; // Part of Cosmos by OpenGenus Foundation struct node { int d; node *left; node *right; }; struct node* newnode(int num) { node *temp = new node; temp->d = num; temp->left = temp->right = NULL; return temp; } void rightview(struct node *root, int level, int *maxlevel) { if (root == NULL) return; if (*maxlevel < level) { cout << root->d << " "; *maxlevel = level; } rightview(root->right, level + 1, maxlevel); rightview(root->left, level + 1, maxlevel); } int main() { struct node *root = newnode(1); root->left = newnode(2); root->right = newnode(3); root->left->left = newnode(4); root->left->right = newnode(5); root->right->left = newnode(6); root->right->right = newnode(7); root->right->left->right = newnode(8); int maxlevel = 0; cout << "\nRight view : "; rightview(root, 1, &maxlevel); cout << endl; return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/traversal/zigzag/zigzag.cpp
#include <iostream> #include <stack> class Node { public: int info; Node* left_child; Node* right_child; Node (int info) : info{info}, left_child{nullptr}, right_child{nullptr} { } }; class BinaryTree { public: Node* root; BinaryTree() : root{nullptr} { } void zigzag_traversal(); }; void BinaryTree :: zigzag_traversal() { std::stack<Node*> st1, st2; st2.push (root); while (!st1.empty() || !st2.empty()) { while (!st1.empty()) { Node* curr = st1.top(); st1.pop(); if (curr->right_child) st2.push (curr->right_child); if (curr->left_child) st2.push (curr->left_child); std::cout << curr->info << " "; } while (!st2.empty()) { Node* curr = st2.top(); st2.pop(); if (curr->left_child) st1.push (curr->left_child); if (curr->right_child) st1.push (curr->right_child); std::cout << curr->info << " "; } } } int main() { BinaryTree binary_tree; binary_tree.root = new Node (1); binary_tree.root->left_child = new Node (2); binary_tree.root->right_child = new Node (3); binary_tree.root->left_child->left_child = new Node (4); binary_tree.root->left_child->right_child = new Node (5); binary_tree.root->right_child->left_child = new Node (6); binary_tree.root->right_child->right_child = new Node (7); binary_tree.zigzag_traversal(); return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/tree/README.md
# Binary tree Description --- A [binary tree](https://en.wikipedia.org/wiki/Binary_tree) is a variation of the [tree](..) data structure, the change being that each node can have a maximum of two children. It is useful for performing [binary searches](../../../search/binary_search), or generating [binary heaps](../../heap) to prepare for [sorting](../../../sorting).
code/data_structures/src/tree/binary_tree/binary_tree/tree/bottom_view_binary_tree/bottom_view_tree.cpp
#include <iostream> #include <map> #include <queue> #include <climits> using namespace std; // Part of Cosmos by OpenGenus Foundation // Tree node class struct Node { int data; //data of the node int hd; //horizontal distance of the node Node *left, *right; //left and right references // Constructor of tree node Node(int key) { data = key; hd = INT_MAX; left = right = NULL; } }; // Method that prints the bottom view. void bottomView(Node *root) { if (root == NULL) return; // Initialize a variable 'hd' with 0 // for the root element. int hd = 0; // TreeMap which stores key value pair // sorted on key value map<int, int> m; // Queue to store tree nodes in level // order traversal queue<Node *> q; // Assign initialized horizontal distance // value to root node and add it to the queue. root->hd = hd; q.push(root); // Loop until the queue is empty (standard // level order loop) while (!q.empty()) { Node *temp = q.front(); q.pop(); // Extract the horizontal distance value // from the dequeued tree node. hd = temp->hd; // Put the dequeued tree node to TreeMap // having key as horizontal distance. Every // time we find a node having same horizontal // distance we need to replace the data in // the map. m[hd] = temp->data; // If the dequeued node has a left child, add // it to the queue with a horizontal distance hd-1. if (temp->left != NULL) { temp->left->hd = hd - 1; q.push(temp->left); } // If the dequeued node has a right child, add // it to the queue with a horizontal distance // hd+1. if (temp->right != NULL) { temp->right->hd = hd + 1; q.push(temp->right); } } // Traverse the map elements using the iterator. for (auto i = m.begin(); i != m.end(); ++i) cout << i->second << " "; } // Driver Code int main() { Node *root = new Node(20); root->left = new Node(8); root->right = new Node(22); root->left->left = new Node(5); root->left->right = new Node(3); root->right->left = new Node(4); root->right->right = new Node(25); root->left->right->left = new Node(10); root->left->right->right = new Node(14); cout << "Bottom view of the given binary tree :\n"; bottomView(root); return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/tree/bottom_view_binary_tree/bottom_view_tree.java
// Java Program to print Bottom View of Binary Tree import java.util.*; import java.util.Map.Entry; // Tree node class class Node { int data; //data of the node int hd; //horizontal distance of the node Node left, right; //left and right references // Constructor of tree node public Node(int key) { data = key; hd = Integer.MAX_VALUE; left = right = null; } } //Tree class class Tree { Node root; //root node of tree // Default constructor public Tree() {} // Parameterized tree constructor public Tree(Node node) { root = node; } // Method that prints the bottom view. public void bottomView() { if (root == null) return; // Initialize a variable 'hd' with 0 for the root element. int hd = 0; // TreeMap which stores key value pair sorted on key value Map<Integer, Integer> map = new TreeMap<>(); // Queue to store tree nodes in level order traversal Queue<Node> queue = new LinkedList<Node>(); // Assign initialized horizontal distance value to root // node and add it to the queue. root.hd = hd; queue.add(root); // Loop until the queue is empty (standard level order loop) while (!queue.isEmpty()) { Node temp = queue.remove(); // Extract the horizontal distance value from the // dequeued tree node. hd = temp.hd; // Put the dequeued tree node to TreeMap having key // as horizontal distance. Every time we find a node // having same horizontal distance we need to replace // the data in the map. map.put(hd, temp.data); // If the dequeued node has a left child add it to the // queue with a horizontal distance hd-1. if (temp.left != null) { temp.left.hd = hd-1; queue.add(temp.left); } // If the dequeued node has a left child add it to the // queue with a horizontal distance hd+1. if (temp.right != null) { temp.right.hd = hd+1; queue.add(temp.right); } } // Extract the entries of map into a set to traverse // an iterator over that. Set<Entry<Integer, Integer>> set = map.entrySet(); // Make an iterator Iterator<Entry<Integer, Integer>> iterator = set.iterator(); // Traverse the map elements using the iterator. while (iterator.hasNext()) { Map.Entry<Integer, Integer> me = iterator.next(); System.out.print(me.getValue()+" "); } } } // Main driver class public class BottomView { public static void main(String[] args) { Node root = new Node(20); root.left = new Node(8); root.right = new Node(22); root.left.left = new Node(5); root.left.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(25); root.left.right.left = new Node(10); root.left.right.right = new Node(14); Tree tree = new Tree(root); System.out.println("Bottom view of the given binary tree:"); tree.bottomView(); } }
code/data_structures/src/tree/binary_tree/binary_tree/tree/tree.c
//Author: Praveen Gupta // Part of Cosmos by OpenGenus Foundation #include<stdio.h> #include<stdlib.h> //Defining Node typedef struct node{ int data; struct node *left; struct node *right; }node; //Creates a new Node node *newNode(int data){ node *temp=(node *)malloc(sizeof(node)); temp->data=data; temp->left=temp->right=NULL; return temp; } //Adds the new node to the appropriate position node *create(node *head,int data){ if (head==NULL){ head = newNode(data); } else if(data<=head->data){ head->left = create(head->left,data); } else{ head->right = create(head->right,data); } return head; } //Prints tree void print(node *head){ if(head==NULL) { return; } printf("%d(",head->data ); print(head->left); printf(" , "); print(head->right); printf(")"); } //Searches for an element in the tree int search(node *head, int data){ if(head==NULL) return 0; if(head->data==data) return 1; if(data<head->data) return search(head->left, data); else return search(head->right, data); } //Deletes a subtree with root as the parameter node *deleteTree(node *head){ if(head==NULL) return NULL; deleteTree(head->left); deleteTree(head->right); free(head); return NULL; } //Deletes the node and its children's node *delete(node *head, int data){ if(head==NULL){ printf("Nor found\n"); } if(head->data==data){ head = deleteTree(head); } else if(data<head->data) head->left = delete(head->left, data); else head->right = delete(head->right, data); return head; } //Finds the height of the tree int height(node *head) { if (head==NULL) return 0; else { /* compute the depth of each subtree */ int left_height = height(head->left); int right_height = height(head->right); /* use the larger one */ if (left_height > right_height) return(left_height+1); else return(right_height+1); } } int main(){ node *head=NULL; printf("Binary Search Tree\n"); int c,data; again: printf("\n1. Insert Node 2. Delete Node 3.Search 4.Find height\n"); scanf("%d",&c); switch(c){ case 1: printf("Enter data\n"); scanf("%d",&data); head=create(head,data); break; case 2: printf("Enter data to delete\n"); scanf("%d",&data); head = delete(head,data); break; case 3: printf("Enter data to search\n"); scanf("%d",&data); search(head,data) ? printf("Found in tree\n"):printf("Not Found in tree\n"); case 4: printf("The height of BST is: %d ",height(head)); } print(head); goto again; return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/tree/tree.cpp
#include <iostream> using namespace std; struct node { int key; struct node *left, *right; }; struct node *newNode(int item) { struct node *temp = new node; temp->key = item; temp->left = temp->right = NULL; return temp; } //Inorder traversal void inorder(struct node *root) { if (root != NULL) { inorder(root->left); cout << root->key << " "; inorder(root->right); } } //Preorder traversal void preorder(struct node *root) { if (root == NULL) return; cout << root->key << " "; preorder(root->left); preorder(root->right); } //Postorder traversal void postorder(struct node *root) { if (root == NULL) return; postorder(root->left); postorder(root->right); cout << root->key << " "; } //Insert key struct node* insert(struct node* node, int key) { if (node == NULL) return newNode(key); if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); return node; } // Driver Code int main() { /* Let us create following BST * 50 * / \ * 30 70 * / \ / \ * 20 40 60 80 */ struct node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); cout << "Inorder traversal: "; inorder(root); cout << "\nPreorder traversal: "; preorder(root); cout << "\nPostorder traversal: "; postorder(root); cout << endl; return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/tree/tree.go
package main // Part of Cosmos by OpenGenus Foundation import "fmt" type Node struct { val int lchild *Node rchild *Node } func (ref *Node) insert(newNode *Node) { if ref.val == newNode.val { return } if ref.val < newNode.val { if ref.rchild == nil { ref.rchild = newNode } else { ref.rchild.insert(newNode) } } else { if ref.lchild == nil { ref.lchild = newNode } else { ref.lchild.insert(newNode) } } } func (ref *Node) inOrder(fn func(n *Node)) { if ref.lchild != nil { ref.lchild.inOrder(fn) } fn(ref) if ref.rchild != nil { ref.rchild.inOrder(fn) } } func max(a, b int) int { if a > b { return a } return b } func getHeight(node *Node) int { if node == nil { return 0 } return max(getHeight(node.lchild), getHeight(node.rchild)) + 1 } type BSTree struct { ref *Node length int } func (BSTree *BSTree) insert(value int) { node := &Node{val: value} if BSTree.ref == nil { BSTree.ref = node } else { BSTree.ref.insert(node) } } func (BSTree *BSTree) inorderPrint() { BSTree.ref.inOrder(func(node *Node) { fmt.Println(node.val) }) } func (BSTree *BSTree) height() int { return getHeight(BSTree.ref) } func main() { tree := new(BSTree) tree.insert(1) tree.insert(0) tree.insert(20) tree.insert(4) tree.insert(5) tree.insert(6) fmt.Println("Height ", tree.height()) tree.inorderPrint() }
code/data_structures/src/tree/binary_tree/binary_tree/tree/tree.java
/* Part of Cosmos by OpenGenus Foundation */ import java.util.ArrayList; class BinaryTree<T extends Comparable<T>>{ private Node<T> root; public BinaryTree(){ root = null; } private Node<T> find(T key){ Node<T> current = root; Node<T> last = root; while(current != null){ last = current; if(key.compareTo(current.data) < 0) current = current.left; else if(key.compareTo(current.data) > 0) current = current.right; //If you find the value return it else return current; } return last; } public void put(T value){ Node<T> newNode = new Node<>(value); if(root == null) root = newNode; else{ //This will return the soon to be parent of the value you're inserting Node<T> parent = find(value); //This if/else assigns the new node to be either the left or right child of the parent if(value.compareTo(parent.data) < 0){ parent.left = newNode; parent.left.parent = parent; return; } else{ parent.right = newNode; parent.right.parent = parent; return; } } } public boolean remove(T value){ //temp is the node to be deleted Node<T> temp = find(value); //If the value doesn't exist if(temp.data != value) return false; //No children if(temp.right == null && temp.left == null){ if(temp == root) root = null; //This if/else assigns the new node to be either the left or right child of the parent else if(temp.parent.data.compareTo(temp.data) < 0) temp.parent.right = null; else temp.parent.left = null; return true; } //Two children else if(temp.left != null && temp.right != null){ Node<T> successor = findSuccessor(temp); //The left tree of temp is made the left tree of the successor successor.left = temp.left; successor.left.parent = successor; //If the successor has a right child, the child's grandparent is it's new parent if(successor.right != null && successor.parent != temp){ successor.right.parent = successor.parent; successor.parent.left = successor.right; successor.right = temp.right; successor.right.parent = successor; } if(temp == root){ successor.parent = null; root = successor; return true; } //If you're not deleting the root else{ successor.parent = temp.parent; //This if/else assigns the new node to be either the left or right child of the parent if(temp.parent.data.compareTo(temp.data) < 0) temp.parent.right = successor; else temp.parent.left = successor; return true; } } //One child else{ //If it has a right child if(temp.right != null){ if(temp == root){ root = temp.right; return true;} temp.right.parent = temp.parent; //Assigns temp to left or right child if(temp.data.compareTo(temp.parent.data) < 0) temp.parent.left = temp.right; else temp.parent.right = temp.right; return true; } //If it has a left child else{ if(temp == root){ root = temp.left; return true;} temp.left.parent = temp.parent; //Assigns temp to left or right side if(temp.data.compareTo(temp.parent.data) < 0) temp.parent.left = temp.left; else temp.parent.right = temp.left; return true; } } } private Node<T> findSuccessor(Node<T> n){ if(n.right == null) return n; Node<T> current = n.right; Node<T> parent = n.right; while(current != null){ parent = current; current = current.left; } return parent; } public T getRoot(){ return root.data; } public String toString() { return inOrder(root).toString(); } private ArrayList<T> inOrder(Node<T> localRoot){ ArrayList<T> temp = new ArrayList<>(); if(localRoot != null){ inOrder(localRoot.left); temp.add(localRoot.data); //System.out.print(localRoot.data + " "); inOrder(localRoot.right); } return temp; } private void preOrder(Node<T> localRoot){ if(localRoot != null){ System.out.print(localRoot.data + " "); preOrder(localRoot.left); preOrder(localRoot.right); } } private void postOrder(Node<T> localRoot){ if(localRoot != null){ postOrder(localRoot.left); postOrder(localRoot.right); System.out.print(localRoot.data + " "); } } private class Node<T extends Comparable<T>>{ public T data; public Node<T> left; public Node<T> right; public Node<T> parent; public Node(T value){ data = value; left = null; right = null; parent = null; } } }
code/data_structures/src/tree/binary_tree/binary_tree/tree/tree.js
/* Part of Cosmos by OpenGenus Foundation */ /*Binary Search Tree!! * * Nodes that will go on the Binary Tree. * They consist of the data in them, the node to the left, the node * to the right, and the parent from which they came from. * * A binary tree is a data structure in which an element * has two successors(children). The left child is usually * smaller than the parent, and the right child is usually * bigger. */ // Node in the tree function Node(val) { this.value = val; this.left = null; this.right = null; } // Search the tree for a value Node.prototype.search = function(val) { if (this.value == val) { return this; } else if (val < this.value && this.left != null) { return this.left.search(val); } else if (val > this.value && this.right != null) { return this.right.search(val); } return null; }; // Visit a node Node.prototype.visit = function() { // Recursively go left if (this.left != null) { this.left.visit(); } // Print out value console.log(this.value); // Recursively go right if (this.right != null) { this.right.visit(); } }; // Add a node Node.prototype.addNode = function(n) { if (n.value < this.value) { if (this.left == null) { this.left = n; } else { this.left.addNode(n); } } else if (n.value > this.value) { if (this.right == null) { this.right = n; } else { this.right.addNode(n); } } }; function Tree() { // Just store the root this.root = null; } // Inorder traversal Tree.prototype.traverse = function() { this.root.visit(); }; // Start by searching the root Tree.prototype.search = function(val) { var found = this.root.search(val); if (found === null) { console.log(val + " not found"); } else { console.log("Found:" + found.value); } }; // Add a new value to the tree Tree.prototype.addValue = function(val) { var n = new Node(val); if (this.root == null) { this.root = n; } else { this.root.addNode(n); } }; //Implementation of BST var bst = new Tree(); bst.addValue(6); bst.addValue(3); bst.addValue(9); bst.addValue(2); bst.addValue(8); bst.addValue(4); bst.traverse(); bst.search(8);
code/data_structures/src/tree/binary_tree/binary_tree/tree/tree.py
## BST operation ## functionalities included are: """ *insert node *delete node *find successor of a node *find minimum in BST *find maximum in BST *traverse in BST(level order traversal) *find height of the BST *search in BST *get node path in BST *find Lowest Common Ancestor in BST(LCA) """ ## class for node creation class Node(object): def __init__(self, data=None): self.left = None self.right = None self.data = data def __str__(self): return str(self.data) ## the Binary Search Tree class class BST(object): def __init__(self): self.root = None def insert(self, val): if self.root == None: print("root!") self.root = Node(val) else: root = self.root while True: if val < root.data: if not root.left: print("left") root.left = Node(val) break else: print("left") root = root.left else: if not root.right: print("right") root.right = Node(val) break else: print("right") root = root.right def insert_recursive(self, root, val): if root == None: return Node(val) else: if val < root.data: node = self.insert_recursive(root.left, val) root.left = node else: node = self.insert_recursive(root.right, val) root.right = node def traverse(self): ## level order traversals nodes = [] nodes.append(self.root) print("\n\nBST representation") while nodes: current = nodes.pop(0) print(current.data) if current.left: nodes.append(current.left) if current.right: nodes.append(current.right) def find_max(self): if self.root is None: return None else: current = self.root while True: if current.right is not None: current = current.right else: break return current.data def find_min(self): if self.root is None: return None else: current = self.root while True: if current.left is not None: current = current.left else: break return current.data def height_(self, root): ## the height driver function if root == None: return 0 else: max_left_subtree_height = self.height_(root.left) max_right_subtree_height = self.height_(root.right) max_height = max(max_left_subtree_height, max_right_subtree_height) + 1 return max_height ## height of the first node is 0 not 1 def height(self): depth = self.height_(self.root) return depth - 1 def search(self, val): if self.root is None: return False else: current = self.root while True: if val < current.data: if current.left: current = current.left else: break elif val > current.data: if current.right: current = current.right else: break if val == current.data: return True return False def get_node_path(self, val): if self.search(val): path = [] current = self.root while True: if current is None: break else: if val == current.data: path.append(current.data) break elif val < current.data: if current.left: path.append(current.data) current = current.left else: break elif val > current.data: if current.right: path.append(current.data) current = current.right else: break return path return None def LCA(self, val1, val2): path1 = self.get_node_path(val1) path2 = self.get_node_path(val2) try: store = None if len(path1) != len(path2): min_list = min(path1, path2, key=len) max_list = max(path1, path2, key=len) min_list, max_list = path1, path2 for lca1 in min_list: for lca2 in max_list: if lca1 == lca2: store = lca1 return store except: return None def successor(self, root): current = root.right while True: if current.left: current = current.left else: break return current def Delete(self, root, val): ## driver function for delettion if root is None: return None else: if val < root.data: root.left = self.Delete(root.left, val) elif val > root.data: root.right = self.Delete(root.right, val) else: if not root.left: right = root.right del root return right if not root.right: left = root.left del root return left else: successor = self.successor(root) root.data = successor.data root.right = self.Delete(root.right, successor.data) return root def delete(self, val): if self.search(val): self.root = self.Delete(self.root, val) else: return "error" def clear(self): print("\n\nre-initializing\n") self.__init__() ## creating an instance for the BST bst = BST() bst.insert(5) bst.insert(9) bst.insert(10)
code/data_structures/src/tree/binary_tree/binary_tree/tree/tree.rb
# Part of Cosmos by OpenGenus Foundation ## # Represents a single node within a binary search tree. class Node attr_accessor :data, :left, :right ## # Initializes a new node with given +data+. # # Params: # +data+:: Data to store within this node. def initialize(data) @data = data @left = nil @right = nil end def to_s @data end end ## # A binary search tree made from generic nodes. class BinarySearchTree ## # Initializes a new binary search tree. def initialize @root = nil end ## # Searchs this binary search tree for the provided +data+. # # Params: # +data+:: Data to search for def search(data) # Start at the root node current = @root puts 'Visiting all nodes...' # Iterate through all nodes while current.data != data puts "Current node: #{current}" # Determine whether to move left or right in tree current = if data < current.data current.left else current.right end # Occurs when the end of the tree is reached. if current.nil? puts "Not found: #{data}" return false end end true end ## # Inserts the given +data+ into the binary search tree. # # Params: # +data+:: Data to insert into BST. def insert(data) # Create new node node = Node.new(data) # Check if tree is empty if @root.nil? @root = node return end current = @root parent = nil # Traverse BST loop do parent = current # Determine whether to place left or right in the tree if data < parent.data current = current.left # Update left node if current.nil? parent.left = node return end else current = current.right # Update right node if current.nil? parent.right = node return end end end end end tree = BinarySearchTree.new tree.insert(15) tree.insert(5) tree.insert(30) tree.insert(25) puts tree.search(5) puts tree.search(10)
code/data_structures/src/tree/binary_tree/binary_tree/tree/tree.swift
// Part of Cosmos by OpenGenus Foundation public enum BinarySearchTree<T: Comparable> { case empty case leaf(T) indirect case node(BinarySearchTree, T, BinarySearchTree) public var count: Int { switch self { case .empty: return 0 case .leaf: return 1 case let .node(left, _, right): return left.count + 1 + right.count } } public var height: Int { switch self { case .empty: return 0 case .leaf: return 1 case let .node(left, _, right): return 1 + max(left.height, right.height) } } public func insert(newValue: T) -> BinarySearchTree { switch self { case .empty: return .leaf(newValue) case .leaf(let value): if newValue < value { return .node(.leaf(newValue), value, .empty) } else { return .node(.empty, value, .leaf(newValue)) } case .node(let left, let value, let right): if newValue < value { return .node(left.insert(newValue), value, right) } else { return .node(left, value, right.insert(newValue)) } } } public func search(x: T) -> BinarySearchTree? { switch self { case .empty: return nil case .leaf(let y): return (x == y) ? self : nil case let .node(left, y, right): if x < y { return left.search(x) } else if y < x { return right.search(x) } else { return self } } } public func contains(x: T) -> Bool { return search(x) != nil } public func minimum() -> BinarySearchTree { var node = self var prev = node while case let .node(next, _, _) = node { prev = node node = next } if case .leaf = node { return node } return prev } public func maximum() -> BinarySearchTree { var node = self var prev = node while case let .node(_, _, next) = node { prev = node node = next } if case .leaf = node { return node } return prev } } extension BinarySearchTree: CustomDebugStringConvertible { public var debugDescription: String { switch self { case .empty: return "." case .leaf(let value): return "\(value)" case .node(let left, let value, let right): return "(\(left.debugDescription) <- \(value) -> \(right.debugDescription))" } } }
code/data_structures/src/tree/binary_tree/binary_tree/tree/tree2.java
public class binary_search_tree { private int value; private binary_search_tree left; private binary_search_tree right; public binary_search_tree(int value) { this.value = value; this.left = null; this.right = null; } public String printInorder(binary_search_tree root) { String result = ""; if(root.left != null) { result = result + root.printInorder(root.left); } result = result + root.value; if(root.right != null) { result = result + root.printInorder(root.right); } return result; } public int height(binary_search_tree root) { if(root == null) { return 0; } int left = 1 + root.height(root.left); int right = 1 + root.height(root.right); if(left > right) { return left; } else { return right; } } public String printPreorder(binary_search_tree root) { String result = ""; result = result + root.value; if(root.left != null) { result = result + root.printPreorder(root.left); } if(root.right != null) { result = result + root.printPreorder(root.right); } return result; } public String printPostorder(binary_search_tree root) { String result = ""; if(root.left != null) { result = result + root.printPostorder(root.left); } if(root.right != null) { result = result + root.printPostorder(root.right); } result = result + root.value; return result; } public binary_search_tree makeNode(int value) { binary_search_tree node = new binary_search_tree(value); return node; } public binary_search_tree addNode(binary_search_tree root, int value) { if(root == null) { root = root.makeNode(value); } else if(root.value == value) { return root; } else if(root.value > value) { if(root.left == null) { root.left = root.makeNode(value); } else { root.left = root.addNode(root.left, value); } } else if(root.value < value) { if(root.right == null) { root.right = root.makeNode(value); } else { root.right = root.addNode(root.right, value); } } return root; } public static void main(String []args) { binary_search_tree tree = null; tree = new binary_search_tree(5); tree = tree.addNode(tree, 3); tree = tree.addNode(tree, 2); tree = tree.addNode(tree, 4); tree = tree.addNode(tree, 7); tree = tree.addNode(tree, 6); tree = tree.addNode(tree, 8); System.out.println("Inorder: " + tree.printInorder(tree)); System.out.println("Postorder: " + tree.printPostorder(tree)); System.out.println("Preorder: " + tree.printPreorder(tree)); System.out.println("Height: " + tree.height(tree)); } }
code/data_structures/src/tree/binary_tree/binary_tree/tree/tree2.swift
public indirect enum BinaryTree<T> { case empty case node(BinaryTree, T, BinaryTree) } extension BinaryTree: CustomStringConvertible { public var description: String { switch self { case let .node(left, value, right): return "value: \(value), left = [\(left.description)], right = [\(right.description)]" case .empty: return "" } } } extension BinaryTree { public func traverseInOrder(process: (T) -> Void) { if case let .node(left, value, right) = self { left.traverseInOrder(process: process) process(value) right.traverseInOrder(process: process) } } public func traversePreOrder(process: (T) -> Void) { if case let .node(left, value, right) = self { process(value) left.traversePreOrder(process: process) right.traversePreOrder(process: process) } } public func traversePostOrder(process: (T) -> Void) { if case let .node(left, value, right) = self { left.traversePostOrder(process: process) right.traversePostOrder(process: process) process(value) } } } extension BinaryTree { func invert() -> BinaryTree { if case let .node(left, value, right) = self { return .node(right.invert(), value, left.invert()) } else { return .empty } } }
code/data_structures/src/tree/binary_tree/inorder_threaded_binary_search_tree/TBT_all_operations.c
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> /* Menu Driven Program with implementation of BST and all the fuctions Insert Traversal(all without using stack/recursion) preorder inorder postorder Delete Exit Program */ struct node { int val; bool lbit; bool rbit; struct node *left; struct node *right; }; struct node *getNode(int val); struct node *insert(struct node *head, int key); struct node *inorderPredecessor(struct node *p); struct node *inorderSuccessor(struct node *p); void Traversal(struct node *head); void inorder(struct node *head); void preorder(struct node *head); struct node *findParent(struct node *p); struct node *postSuccessor(struct node *p); void postorder(struct node *head); // ********************************* DELETE ******************************** struct node *delThreadedBST(struct node *head, int key); struct node *delTwoChild(struct node *head, struct node *par, struct node *ptr); struct node *delOneChild(struct node *head, struct node *par, struct node *ptr); struct node *delNoChild(struct node *head, struct node *par, struct node *ptr); int main() { struct node *head; head = (struct node *)malloc(sizeof(struct node)); head->lbit = 0; head->rbit = 1; // convention for all cases head->right = head; // convention for all cases head->left = head; // head->left should point to root /* uncomment the following to create a sample tree like insert(head,10); insert(head,5); insert(head,15); insert(head,20); insert(head,13); insert(head,14); insert(head,12); insert(head,8); insert(head,3); insert(head, 21); insert(head, 22); insert(head, 30); will create a tree like this 10 5 15 3 8 13 20 12 14 21 22 30 or use menu driven approach */ while (1) { printf("\n\n\n\n****************************************************************"); printf("\nSelect operation"); printf("\n\t1.Insert\n\t2.Traverse(pre in)\n\t3.Delete\n\n\t0.Exit\n\nEnter your choice: "); int n; scanf("%d", &n); int temp; /*system("cls");*/ switch (n) { case 1: { printf("\nEnter number to Insert: "); scanf("%d", &temp); head = insert(head, temp); } break; case 2: Traversal(head); break; case 3: { printf("\nEnter number to Delete: "); scanf("%d", &temp); delThreadedBST(head, temp); } break; case 0: exit(0); break; default: printf("invalid Choixe."); break; } } return 0; } struct node * getNode(int val) { struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->val = val; temp->lbit = 0; temp->rbit = 0; temp->left = NULL; temp->right = NULL; return temp; } struct node * insert(struct node *head, int key) { struct node *temp = getNode(key); struct node *p; if (head->left == head) { head->left = temp; temp->left = head; temp->right = head; return head; } p = head->left; while (1) { if (key < p->val && p->lbit == 1) p = p->left; else if (key > p->val && p->rbit == 1) p = p->right; else break; } if (key < p->val) { p->lbit = 1; temp->left = p->left; temp->right = p; p->left = temp; } else if (key > p->val) { p->rbit = 1; // rearrange the thread after linking new node temp->right = p->right; // inorder successor (next) temp->left = p; p->right = temp; } return head; } struct node * inorderPredecessor(struct node *p) { if (p->lbit == 0) return p->left; else if (p->lbit == 1) { p = p->left; while (p->rbit == 1) p = p->right; } return p; } struct node * inorderSuccessor(struct node *p) { if (p->rbit == 0) return p->right; else if (p->rbit == 1) { p = p->right; while (p->lbit == 1) p = p->left; } return p; } void inorder(struct node *head) { struct node *p; p = head->left; while (p->lbit == 1) p = p->left; while (p != head) { printf(" %d", p->val); p = inorderSuccessor(p); } } void preorder(struct node *head) { struct node *p; p = head->left; while (p != head) { printf("%d ", p->val); if (p->lbit == 1) { p = p->left; } else if (p->rbit == 1) { p = p->right; } else if (p->rbit == 0) { while (p->rbit == 0) p = p->right; p = p->right; } } } struct node * findParent(struct node *p) { struct node *child = p; // ancestor of child while (p->rbit == 1) p = p->right; p = p->right; if (p->left == child) return p; p = p->left; while (p->right != child) { p = p->right; } return p; } struct node * postSuccessor(struct node *p) { struct node *cur = p; struct node *parent = findParent(cur); // printf("suc %d\n", parent->val); if (parent->right == cur) return parent; else { while (p->rbit == 1) p = p->right; p = p->right; if (p->rbit == 1) { p = p->right; while (!(p->rbit == 0 && p->lbit == 0)) { if (p->lbit == 1) p = p->left; else if (p->rbit == 1) p = p->right; } } // printf("suc %d\n", p->val); } return p; } void postorder(struct node *head) { struct node *p = head->left; struct node *temp = p; while (!(p->rbit == 0 && p->lbit == 0)) { if (p->lbit == 1) { p = p->left; } else if (p->rbit == 1) p = p->right; } printf(" %d", p->val); while (p != head->left) { // printf(" hello\n"); p = postSuccessor(p); printf(" %d", p->val); } } void Traversal(struct node *head) { printf("\nTraversal Type : \n1.preorder\n2.Inorder\n3.PostOrder\n\n\nEnter your choice: "); int n; scanf("%d", &n); // system("cls"); switch (n) { case 1: printf("\nPreorder:\n\t"); preorder(head); break; case 2: printf("\nInorder:\n\t"); inorder(head); break; case 3: printf("\nPostorder:\n\t"); postorder(head); break; default: break; } } /* ********************************* DELETE ******************************** */ struct node * delThreadedBST(struct node *head, int key) { struct node *par = head, *ptr = head->left; bool found = 0; while (ptr != head) { if (key == ptr->val) { found = 1; break; } par = ptr; if (key < ptr->val) { if (ptr->lbit == 1) ptr = ptr->left; else break; } else { if (ptr->rbit == 1) ptr = ptr->right; else break; } } if (found == 0) printf("key not present in tree\n"); else if (ptr->lbit == 1 && ptr->rbit == 1) head = delTwoChild(head, par, ptr); else if (ptr->lbit == 0 && ptr->rbit == 0) head = delNoChild(head, par, ptr); else head = delOneChild(head, par, ptr); return head; } struct node * delTwoChild(struct node *head, struct node *par, struct node *ptr) { struct node *parSuc = ptr; struct node *suc = ptr->right; while (suc->lbit == 1) { parSuc = suc; suc = suc->left; } ptr->val = suc->val; if (suc->lbit == 0 && suc->rbit == 0) head = delNoChild(head, parSuc, suc); else head = delOneChild(head, parSuc, suc); return head; } struct node * delOneChild(struct node *head, struct node *par, struct node *ptr) { struct node *child; if (ptr->lbit == 1) child = ptr->left; else child = ptr->right; struct node *p = inorderPredecessor(ptr); struct node *s = inorderSuccessor(ptr); if (ptr == par->left) { par->left = child; } else { par->right = child; } if (ptr->lbit == 1) p->right = s; else if (ptr->rbit == 1) s->left = p; free(ptr); return head; } struct node * delNoChild(struct node *head, struct node *par, struct node *ptr) { if (ptr == head->left) { ptr = NULL; } else if (ptr == par->left) { par->lbit = 0; par->left = ptr->left; } else if (ptr == par->right) { par->rbit = 0; par->right = ptr->right; } free(ptr); return head; }
code/data_structures/src/tree/binary_tree/rope/rope.py
class node: def __init__(self, data=None): self.data = data if not data: self.weight = 0 else: self.weight = len(data) self.left = None self.right = None self.parent = None def size(self): if self.data: return len(self.data) tmp = self.weight if self.right: return tmp + self.right.size() def addChild(self, side, node): node.parent = self nodeSize = node.size() if side == "left": self.left = node self.weight = nodeSize elif side == "right": self.right = node tmp = self while tmp.parent: if tmp.parent.left == tmp: tmp.parent.weight += nodeSize tmp = tmp.parent def removeChild(self, side): result = None if side == "left": result = self.left self.left = None self.weight = 0 elif side == "right": result = self.right self.right = None nodeSize = result.size() tmp = self while tmp.parent: if tmp.parent.left == tmp: tmp.parent.weight -= nodeSize tmp = tmp.parent return result class Rope: def __init__(self, text=None): if text: self.head = node(text) else: self.head = node() def Index(self, ind, node=None): if node is None: node = self.head if node.weight <= ind: return self.Index(ind - node.weight, node.right) elif node.left: return self.Index(ind, node.left) else: return node.data[ind] def concat(self, rope): result = Rope() result.head.addChild("left", self.head) result.head.addChild("right", rope.head) self.head = result.head def split(self, ind): result = Rope() tmp = self.head splitOff = list() # Lookup the node with the index while True: if tmp.weight <= ind and tmp.right: ind = ind - tmp.weight tmp = tmp.right elif tmp.left: tmp = tmp.left else: break # Split that node if the split point is in a node if ind != 0: node1 = node(tmp.data[:ind]) node2 = node(tmp.data[ind:]) nodeParent = node() nodeParent.addChildLeft(node1) nodeParent.addChildRight(node2) if tmp.parent.left == tmp: tmp = tmp.parent tmp.removeChild("left") tmp.addChild("left", nodeParent) tmp = nodeParent.right else: tmp = tmp.parent tmp.removeChild("right") tmp.addChild("right", nodeParent) tmp = nodeParent.right # Get everything else to the right of ind first = True while tmp.parent: if not tmp.parent.left: tmp = tmp.parent elif tmp.parent.left == tmp: if tmp.parent.right: splitOff.append(tmp.parent.removeChild("right")) else: tmp = tmp.parent elif tmp.parent.right == tmp and first: first = False tmp = tmp.parent splitOff.append(tmp.removeChild("right")) # Make a rope with the content right of ind to return rightRope = rope() while len(splitOff) > 0: rightRope.insert(0, splitOff.pop(0)) return rightRope def insert(self, ind, rope): rightSide = self.split(ind) self.concat(rope) self.concat(rightSide) def delete(self, ind_left, ind_right): rightSide = self.split(ind_right) self.split(ind_left) self.concat(rightSide) ROPE = Rope()
code/data_structures/src/tree/binary_tree/treap/persistent_treap.kt
/** * Fully persistent Treap implementation (Allows all operations in any version) * Average complexity for insert, search and remove is O(log N) * It uses O(N * log N) memory. */ import java.util.* class TreapNode<T : Comparable<T>> { val value: T val priority: Int val leftChild: TreapNode<T>? val rightChild: TreapNode<T>? constructor(value: T, priority: Int, leftChild: TreapNode<T>?, rightChild: TreapNode<T>?) { this.value = value this.priority = priority this.leftChild = leftChild this.rightChild = rightChild } constructor(value: T, leftChild: TreapNode<T>?, rightChild: TreapNode<T>?) : this(value, Random().nextInt(), leftChild, rightChild) fun cloneReplaceLeft(leftChild: TreapNode<T>?): TreapNode<T> { return TreapNode(this.value, this.priority, leftChild, this.rightChild) } fun cloneReplaceRight(rightChild: TreapNode<T>?): TreapNode<T> { return TreapNode(this.value, this.priority, this.leftChild, rightChild) } } class PersistentTreap<T : Comparable<T>>(private val root: TreapNode<T>? = null) { fun insert(value: T): PersistentTreap<T> { return PersistentTreap(insert(root, value)) } fun remove(value: T): PersistentTreap<T> { return PersistentTreap(remove(root, value)) } fun search(value: T): Boolean { return search(root, value) } fun inorder(): List<T> { return inorder(root) } fun dump() { if (root == null) println("Empty tree") else dump(root, 0) } private fun dump(currentNode: TreapNode<T>?, offset: Int) { if (currentNode != null) { dump(currentNode.rightChild, offset + 1) print(" ".repeat(offset)) print(String.format("%s\t %20d\n", currentNode.value.toString(), currentNode.priority)) dump(currentNode.leftChild, offset + 1) } } private fun inorder(currentNode: TreapNode<T>?): List<T> { if (currentNode == null) return listOf() val list: MutableList<T> = mutableListOf() list.addAll(inorder(currentNode.leftChild)) list.add(currentNode.value) list.addAll(inorder(currentNode.rightChild)) return list } private fun rotateLeft(currentNode: TreapNode<T>?): TreapNode<T>? { return currentNode?.rightChild?.cloneReplaceLeft( currentNode.cloneReplaceRight(currentNode.rightChild.leftChild)) } private fun rotateRight(currentNode: TreapNode<T>?): TreapNode<T>? { return currentNode?.leftChild?.cloneReplaceRight( currentNode.cloneReplaceLeft(currentNode.leftChild.rightChild) ) } private fun balance(currentNode: TreapNode<T>?): TreapNode<T>? { if (currentNode == null) return null if (currentNode.leftChild != null && currentNode.leftChild.priority > currentNode.priority) return rotateRight(currentNode) if (currentNode.rightChild != null && currentNode.rightChild.priority > currentNode.priority) return rotateLeft(currentNode) return currentNode } private fun insert(currentNode: TreapNode<T>?, value: T): TreapNode<T>? { if (currentNode == null) return TreapNode(value, null, null) return balance( if (value <= currentNode.value) currentNode.cloneReplaceLeft(insert(currentNode.leftChild, value)) else currentNode.cloneReplaceRight(insert(currentNode.rightChild, value)) ) } private fun remove(currentNode: TreapNode<T>?, value: T): TreapNode<T>? { if (currentNode == null || (currentNode.leftChild == null && currentNode.rightChild == null && currentNode.value == value)) return null return when { value < currentNode.value -> currentNode.cloneReplaceLeft(remove(currentNode.leftChild, value)) value > currentNode.value -> currentNode.cloneReplaceRight(remove(currentNode.rightChild, value)) else -> if (currentNode.leftChild == null || (currentNode.rightChild != null && currentNode.rightChild.priority > currentNode.leftChild.priority)) with (rotateLeft(currentNode)!!) { cloneReplaceLeft(remove(leftChild, value)) } else with (rotateRight(currentNode)!!) { cloneReplaceRight(remove(rightChild, value)) } } } private fun search(currentNode: TreapNode<T>?, value: T): Boolean { if (currentNode == null) return false return when { value < currentNode.value -> search(currentNode.leftChild, value) value > currentNode.value -> search(currentNode.rightChild, value) else -> true } } } fun <T : Comparable<T>> List<T>.isSorted(): Boolean { return (0 until this.size-1).none { this[it] > this[it +1] } } fun main(args: Array<String>) { val scan = Scanner(System.`in`) val treapVersions: MutableList<PersistentTreap<Int>> = mutableListOf() var currentTreap = PersistentTreap<Int>() treapVersions.add(currentTreap) println("Treap Test\n") /** Perform tree operations **/ loop@ while (true) { println("\nTreap Operations\n") println("1. insert ") println("2. delete ") println("3. search") println("4. show tree") println("5. exit") print("Choose version: ") val version = scan.nextInt() if (version >= treapVersions.size) { println("Version $version does not exist") continue } currentTreap = treapVersions[version] print("Choose operation: ") val choice = scan.nextInt() when (choice) { 1 -> { println("Enter integer element to insert") currentTreap = currentTreap.insert(scan.nextInt()) } 2 -> { println("Enter integer element to delete") currentTreap = currentTreap.remove(scan.nextInt()) } 3 -> { println("Enter integer element to search") println("Search result : " + currentTreap.search(scan.nextInt())) } 4 -> currentTreap.dump() 5 -> break@loop else -> println("Invalid operation") } if (!currentTreap.inorder().isSorted()) println("SOMETHING WENT WRONG") if (choice == 1 || choice == 2) { println("Created version ${treapVersions.size}") treapVersions.add(currentTreap) } } }
code/data_structures/src/tree/binary_tree/treap/treap.cpp
#include <iostream> #define ll long long #define MOD 1000000007 using namespace std; // Part of Cosmos by OpenGenus Foundation // structure representing a treap node struct node { ll key; ll priority; node* left; node* right; node* parent; node(ll data) { key = data; priority = (1LL * rand()) % MOD; left = right = parent = NULL; } }; // function to left-rotate the subtree rooted at x void left_rotate(node* &root, node* x) { node* y = x->right; x->right = y->left; if (y->left != NULL) y->left->parent = x; y->parent = x->parent; if (x->parent == NULL) root = y; else if (x->key > x->parent->key) x->parent->right = y; else x->parent->left = y; y->left = x; x->parent = y; } // function to right-rotate the subtree rooted at x void right_rotate(node* &root, node* x) { node* y = x->left; x->left = y->right; if (y->right != NULL) y->right->parent = x; y->parent = x->parent; if (x->parent == NULL) root = y; else if (x->key > x->parent->key) x->parent->right = y; else x->parent->left = y; y->right = x; x->parent = y; } // function to restore min-heap property by rotations void treap_insert_fixup(node* &root, node* z) { while (z->parent != NULL && z->parent->priority > z->priority) { // if z is a right child if (z->key > z->parent->key) left_rotate(root, z->parent); // if z is a left child else right_rotate(root, z->parent); } } // function to insert a node into the treap // performs simple BST insert and calls treap_insert_fixup void insert(node* &root, ll data) { node *x = root, *y = NULL; while (x != NULL) { y = x; if (data < x->key) x = x->left; else x = x->right; } node* z = new node(data); z->parent = y; if (y == NULL) root = z; else if (z->key > y->key) y->right = z; else y->left = z; treap_insert_fixup(root, z); } void preorder(node* root) { if (root) { cout << root->key << " "; preorder(root->left); preorder(root->right); } } // free the allocated memory void delete_treap(node* root) { if (root) { delete_treap(root->left); delete_treap(root->right); delete root; } } int main() { node* root = NULL; int choice; ll key; while (true) { cout << "1. Insert 2. Preorder 3. Quit\n"; cin >> choice; if (choice == 1) { cout << "Enter key : "; cin >> key; insert(root, key); } else if (choice == 2) { preorder(root); cout << endl; } else break; } delete_treap(root); return 0; }
code/data_structures/src/tree/binary_tree/treap/treap.java
/** * Part of Cosmos by OpenGenus Foundation **/ import java.util.Scanner; import java.util.Random; /** Class TreapNode **/ class TreapNode { TreapNode left, right; int priority, element; /** Constructor **/ public TreapNode() { this.element = 0; this.left = this; this.right = this; this.priority = Integer.MAX_VALUE; } /** Constructor **/ public TreapNode(int ele) { this(ele, null, null); } /** Constructor **/ public TreapNode(int ele, TreapNode left, TreapNode right) { this.element = ele; this.left = left; this.right = right; this.priority = new Random().nextInt( ); } } /** Class TreapTree **/ class TreapTree { private TreapNode root; private static TreapNode nil = new TreapNode(); /** Constructor **/ public TreapTree() { root = nil; } /** Function to check if tree is empty **/ public boolean isEmpty() { return root == nil; } /** Make the tree logically empty **/ public void makeEmpty() { root = nil; } /** Functions to insert data **/ public void insert(int X) { root = insert(X, root); } private TreapNode insert(int X, TreapNode T) { if (T == nil) return new TreapNode(X, nil, nil); else if (X < T.element) { T.left = insert(X, T.left); if (T.left.priority < T.priority) { TreapNode L = T.left; T.left = L.right; L.right = T; return L; } } else if (X > T.element) { T.right = insert(X, T.right); if (T.right.priority < T.priority) { TreapNode R = T.right; T.right = R.left; R.left = T; return R; } } return T; } /** Functions to count number of nodes **/ public int countNodes() { return countNodes(root); } private int countNodes(TreapNode r) { if (r == nil) return 0; else { int l = 1; l += countNodes(r.left); l += countNodes(r.right); return l; } } /** Functions to search for an element **/ public boolean search(int val) { return search(root, val); } private boolean search(TreapNode r, int val) { boolean found = false; while ((r != nil) && !found) { int rval = r.element; if (val < rval) r = r.left; else if (val > rval) r = r.right; else { found = true; break; } found = search(r, val); } return found; } /** Function for inorder traversal **/ public void inorder() { inorder(root); } private void inorder(TreapNode r) { if (r != nil) { inorder(r.left); System.out.print(r.element +" "); inorder(r.right); } } /** Function for preorder traversal **/ public void preorder() { preorder(root); } private void preorder(TreapNode r) { if (r != nil) { System.out.print(r.element +" "); preorder(r.left); preorder(r.right); } } /** Function for postorder traversal **/ public void postorder() { postorder(root); } private void postorder(TreapNode r) { if (r != nil) { postorder(r.left); postorder(r.right); System.out.print(r.element +" "); } } } /** Class TreapTest **/ public class Treap { public static void main(String[] args) { Scanner scan = new Scanner(System.in); /** Creating object of Treap **/ TreapTree trpt = new TreapTree(); System.out.println("Treap Test\n"); char ch; /** Perform tree operations **/ do { System.out.println("\nTreap Operations\n"); System.out.println("1. insert "); System.out.println("2. search"); System.out.println("3. count nodes"); System.out.println("4. check empty"); System.out.println("5. clear"); int choice = scan.nextInt(); switch (choice) { case 1 : System.out.println("Enter integer element to insert"); trpt.insert( scan.nextInt() ); break; case 2 : System.out.println("Enter integer element to search"); System.out.println("Search result : "+ trpt.search( scan.nextInt() )); break; case 3 : System.out.println("Nodes = "+ trpt.countNodes()); break; case 4 : System.out.println("Empty status = "+ trpt.isEmpty()); break; case 5 : System.out.println("\nTreap Cleared"); trpt.makeEmpty(); break; default : System.out.println("Wrong Entry \n "); break; } /** Display tree **/ System.out.print("\nPost order : "); trpt.postorder(); System.out.print("\nPre order : "); trpt.preorder(); System.out.print("\nIn order : "); trpt.inorder(); System.out.println("\nDo you want to continue (Type y or n) \n"); ch = scan.next().charAt(0); } while (ch == 'Y'|| ch == 'y'); } }
code/data_structures/src/tree/binary_tree/treap/treap.scala
import java.util.Random case class Treap[T](el: T, priority: Int, left: Treap[T], right: Treap[T]) { // extends Treap[T] { def contains(target: T)(implicit ord: Ordering[T]): Boolean = { if (target == el) { true } else if (ord.lt(target, el)) { if (left == null) false else left.contains(target) } else { if (right == null) false else right.contains(target) } } def insert(newEl: T)(implicit ord: Ordering[T]): Treap[T] = insert(newEl, new Random().nextInt()) def insert(newEl: T, newPriority: Int)(implicit ord: Ordering[T]): Treap[T] = { if (newEl == el) { this } else if (ord.lt(newEl, el)) { val newTreap = if (left == null) { this.copy(left = Treap(newEl, newPriority, null, null)) } else { this.copy(left = left.insert(newEl, newPriority)) } if (newTreap.left.priority > priority) { // rotate right to raise node with higer priority val leftChild = newTreap.left leftChild.copy(right = newTreap.copy(left = leftChild.right)) } else { newTreap } } else { val newTreap = if (right == null) { this.copy(right = Treap(newEl, newPriority, null, null)) } else { this.copy(right = right.insert(newEl, newPriority)) } if (newTreap.right.priority > priority) { // rotate left to raise node with higer priority val rightChild = newTreap.right rightChild.copy(left = newTreap.copy(right = rightChild.left)) } else { newTreap } } } def inOrder(visitor: (T, Int) => Unit): Unit = { if (left != null) left.inOrder(visitor); visitor(el, priority) if (right != null) right.inOrder(visitor); } } object Main { def main(args: Array[String]): Unit = { Treap("a", 100, null, null).insert("b").insert("c").inOrder((el: String, priority: Int) => println((el, priority))) Treap("a", 100, null, null).insert("c").insert("c").inOrder((el: String, priority: Int) => println((el, priority))) Treap("a", 100, null, null).insert("c").insert("b").inOrder((el: String, priority: Int) => println((el, priority))) println(Treap("a", 100, null, null).insert("c").insert("b").contains("e")) println(Treap("a", 100, null, null).insert("c").insert("b").contains("b")) println(Treap("a", 100, null, null).insert("c").insert("b").contains("a")) } }
code/data_structures/src/tree/binary_tree/treap/treap.swift
// Part of Cosmos by OpenGenus Foundation import Foundation public indirect enum Treap<Key: Comparable, Element> { case empty case node(key: Key, val: Element, p: Int, left: Treap, right: Treap) public init() { self = .empty } internal func get(_ key: Key) -> Element? { switch self { case .empty: return nil case let .node(treeKey, val, _, _, _) where treeKey == key: return val case let .node(treeKey, _, _, left, _) where key < treeKey: return left.get(key) case let .node(treeKey, _, _, _, right) where key > treeKey: return right.get(key) default: return nil } } public func contains(_ key: Key) -> Bool { switch self { case .empty: return false case let .node(treeKey, _, _, _, _) where treeKey == key: return true case let .node(treeKey, _, _, left, _) where key < treeKey: return left.contains(key) case let .node(treeKey, _, _, _, right) where key > treeKey: return right.contains(key) default: return false } } public var depth: Int { switch self { case .empty: return 0 case let .node(_, _, _, left, .empty): return 1 + left.depth case let .node(_, _, _, .empty, right): return 1 + right.depth case let .node(_, _, _, left, right): let leftDepth = left.depth let rightDepth = right.depth return 1 + leftDepth > rightDepth ? leftDepth : rightDepth } } public var count: Int { return Treap.countHelper(self) } fileprivate static func countHelper(_ treap: Treap<Key, Element>) -> Int { if case let .node(_, _, _, left, right) = treap { return countHelper(left) + 1 + countHelper(right) } return 0 } } internal func leftRotate<Key: Comparable, Element>(_ tree: Treap<Key, Element>) -> Treap<Key, Element> { if case let .node(key, val, p, .node(leftKey, leftVal, leftP, leftLeft, leftRight), right) = tree { return .node(key: leftKey, val: leftVal, p: leftP, left: leftLeft, right: Treap.node(key: key, val: val, p: p, left: leftRight, right: right)) } else { return .empty } } internal func rightRotate<Key: Comparable, Element>(_ tree: Treap<Key, Element>) -> Treap<Key, Element> { if case let .node(key, val, p, left, .node(rightKey, rightVal, rightP, rightLeft, rightRight)) = tree { return .node(key: rightKey, val: rightVal, p: rightP, left: Treap.node(key: key, val: val, p: p, left: left, right: rightLeft), right: rightRight) } else { return .empty } } public extension Treap { internal func set(key: Key, val: Element, p: Int = Int(arc4random())) -> Treap { switch self { case .empty: return .node(key: key, val: val, p: p, left: .empty, right: .empty) case let .node(nodeKey, nodeVal, nodeP, left, right) where key != nodeKey: return insertAndBalance(nodeKey, nodeVal, nodeP, left, right, key, val, p) case let .node(nodeKey, _, nodeP, left, right) where key == nodeKey: return .node(key: key, val: val, p: nodeP, left: left, right: right) default: return .empty } } fileprivate func insertAndBalance(_ nodeKey: Key, _ nodeVal: Element, _ nodeP: Int, _ left: Treap, _ right: Treap, _ key: Key, _ val: Element, _ p: Int) -> Treap { let newChild: Treap<Key, Element> let newNode: Treap<Key, Element> let rotate: (Treap) -> Treap if key < nodeKey { newChild = left.set(key: key, val: val, p: p) newNode = .node(key: nodeKey, val: nodeVal, p: nodeP, left: newChild, right: right) rotate = leftRotate } else if key > nodeKey { newChild = right.set(key: key, val: val, p: p) newNode = .node(key: nodeKey, val: nodeVal, p: nodeP, left: left, right: newChild) rotate = rightRotate } else { newChild = .empty newNode = .empty return newNode } if case let .node(_, _, newChildP, _, _) = newChild, newChildP < nodeP { return rotate(newNode) } else { return newNode } } internal func delete(key: Key) throws -> Treap { switch self { case .empty: throw NSError(domain: "com.wta.treap.errorDomain", code: -1, userInfo: nil) case let .node(nodeKey, val, p, left, right) where key < nodeKey: return try Treap.node(key: nodeKey, val: val, p: p, left: left.delete(key: key), right: right) case let .node(nodeKey, val, p, left, right) where key > nodeKey: return try Treap.node(key: nodeKey, val: val, p: p, left: left, right: right.delete(key: key)) case let .node(_, _, _, left, right): return merge(left, right: right) } } }
code/data_structures/src/tree/heap/README.md
# Heap Description --- Heap is a special case of balanced binary tree data structure where the root-node key is compared with its children and arranged accordingly. If a has child node b then - key(a) <= key(b) If the value of parent is lesser than that of child, this property generates **Min Heap** otherwise it generates a **Max Heap** Heap API --- - **extractTop()**: Removes top element from the heap - **insert()**: Inserts an item to the heap - **top()**: Returns the top element of the heap (the minimum or maximum value) - **empty()**: Checks if the heap is empty Time Complexity --- extractTop() and insert() take O(log n) and the others take O(1). Example folders --- **max_heap**: Various implementations of a Max Heap. **min_heap**: Various implementations of a Min Heap **priority_queue**: Priority Queue implementations using a heap
code/data_structures/src/tree/heap/binomial_heap/binomial_heap.c
/* C program to implement Binomial Heap tree */ #include<stdio.h> #include<stdlib.h> struct node { int n; int degree; struct node* parent; struct node* child; struct node* sibling; }; struct node* MAKE_bin_HEAP(); void bin_LINK(struct node*, struct node*); struct node* CREATE_NODE(int); struct node* bin_HEAP_UNION(struct node*, struct node*); struct node* bin_HEAP_INSERT(struct node*, struct node*); struct node* bin_HEAP_MERGE(struct node*, struct node*); struct node* bin_HEAP_EXTRACT_MIN(struct node*); void REVERT_LIST(struct node*); int DISPLAY(struct node*); struct node* FIND_NODE(struct node*, int); int bin_HEAP_DECREASE_KEY(struct node*, int, int); int bin_HEAP_DELETE(struct node*, int); int count = 1; struct node* MAKE_bin_HEAP() { struct node* np; np = NULL; return np; } struct node * H = NULL; struct node *Hr = NULL; void bin_LINK(struct node* y, struct node* z) { y->parent = z; y->sibling = z->child; z->child = y; z->degree = z->degree + 1; } struct node* CREATE_NODE(int k) { struct node* p;//new node; p = (struct node*) malloc(sizeof(struct node)); p->n = k; return p; } struct node* bin_HEAP_UNION(struct node* H1, struct node* H2) { struct node* prev_x; struct node* next_x; struct node* x; struct node* H = MAKE_bin_HEAP(); H = bin_HEAP_MERGE(H1, H2); if (H == NULL) return H; prev_x = NULL; x = H; next_x = x->sibling; while (next_x != NULL) { if ((x->degree != next_x->degree) || ((next_x->sibling != NULL) && (next_x->sibling)->degree == x->degree)) { prev_x = x; x = next_x; } else { if (x->n <= next_x->n) { x->sibling = next_x->sibling; bin_LINK(next_x, x); } else { if (prev_x == NULL) H = next_x; else prev_x->sibling = next_x; bin_LINK(x, next_x); x = next_x; } } next_x = x->sibling; } return H; } struct node* bin_HEAP_INSERT(struct node* H, struct node* x) { struct node* H1 = MAKE_bin_HEAP(); x->parent = NULL; x->child = NULL; x->sibling = NULL; x->degree = 0; H1 = x; H = bin_HEAP_UNION(H, H1); return H; } struct node* bin_HEAP_MERGE(struct node* H1, struct node* H2) { struct node* H = MAKE_bin_HEAP(); struct node* y; struct node* z; struct node* a; struct node* b; y = H1; z = H2; if (y != NULL) { if (z != NULL && y->degree <= z->degree) H = y; else if (z != NULL && y->degree > z->degree) /* need some modifications here;the first and the else conditions can be merged together!!!! */ H = z; else H = y; } else H = z; while (y != NULL && z != NULL) { if (y->degree < z->degree) { y = y->sibling; } else if (y->degree == z->degree) { a = y->sibling; y->sibling = z; y = a; } else { b = z->sibling; z->sibling = y; z = b; } } return H; } int DISPLAY(struct node* H) { struct node* p; if (H == NULL) { printf("\nHEAP EMPTY"); return 0; } printf("\nTHE ROOT NODES ARE:-\n"); p = H; while (p != NULL) { printf("%d", p->n); if (p->sibling != NULL) printf("-->"); p = p->sibling; } printf("\n"); return 1; } struct node* bin_HEAP_EXTRACT_MIN(struct node* H1) { int min; struct node* t = NULL; struct node* x = H1; struct node *Hr; struct node* p; Hr = NULL; if (x == NULL) { printf("\nNOTHING TO EXTRACT"); return x; } // int min=x->n; p = x; while (p->sibling != NULL) { if ((p->sibling)->n < min) { min = (p->sibling)->n; t = p; x = p->sibling; } p = p->sibling; } if (t == NULL && x->sibling == NULL) H1 = NULL; else if (t == NULL) H1 = x->sibling; else if (t->sibling == NULL) t = NULL; else t->sibling = x->sibling; if (x->child != NULL) { REVERT_LIST(x->child); (x->child)->sibling = NULL; } H = bin_HEAP_UNION(H1, Hr); return x; } void REVERT_LIST(struct node* y) { if (y->sibling != NULL) { REVERT_LIST(y->sibling); (y->sibling)->sibling = y; } else { Hr = y; } } struct node* FIND_NODE(struct node* H, int k) { struct node* x = H; struct node* p = NULL; if (x->n == k) { p = x; return p; } if (x->child != NULL && p == NULL) { p = FIND_NODE(x->child, k); } if (x->sibling != NULL && p == NULL) { p = FIND_NODE(x->sibling, k); } return p; } int bin_HEAP_DECREASE_KEY(struct node* H, int i, int k) { int temp; struct node* p; struct node* y; struct node* z; p = FIND_NODE(H, i); if (p == NULL) { printf("\nINVALID CHOICE OF KEY TO BE REDUCED"); return 0; } if (k > p->n) { printf("\nSORY!THE NEW KEY IS GREATER THAN CURRENT ONE"); return 0; } p->n = k; y = p; z = p->parent; while (z != NULL && y->n < z->n) { temp = y->n; y->n = z->n; z->n = temp; y = z; z = z->parent; } printf("\nKEY REDUCED SUCCESSFULLY!"); return 1; } int bin_HEAP_DELETE(struct node* H, int k) { struct node* np; if (H == NULL) { printf("\nHEAP EMPTY"); return 0; } bin_HEAP_DECREASE_KEY(H, k, -1000); np = bin_HEAP_EXTRACT_MIN(H); if (np != NULL) { printf("\nNODE DELETED SUCCESSFULLY"); return 1; } return 0; } int main() { int i, n, m, l; struct node* p; struct node* np; char ch; printf("\nENTER THE NUMBER OF ELEMENTS:"); scanf("%d", &n); printf("\nENTER THE ELEMENTS:\n"); for (i = 1; i <= n; i++) { scanf("%d", &m); np = CREATE_NODE(m); H = bin_HEAP_INSERT(H, np); } DISPLAY(H); do { printf("\nMENU:-\n"); printf( "\n1)INSERT AN ELEMENT\n2)EXTRACT THE MINIMUM KEY NODE\n3)DECREASE A NODE KEY\n4)DELETE A NODE\n5)QUIT\n"); scanf("%d", &l); switch (l) { case 1: do { printf("\nENTER THE ELEMENT TO BE INSERTED:"); scanf("%d", &m); p = CREATE_NODE(m); H = bin_HEAP_INSERT(H, p); printf("\nNOW THE HEAP IS:\n"); DISPLAY(H); printf("\nINSERT MORE(y/Y)= \n"); fflush(stdin); scanf("%c", &ch); } while (ch == 'Y' || ch == 'y'); break; case 2: do { printf("\nEXTRACTING THE MINIMUM KEY NODE"); p = bin_HEAP_EXTRACT_MIN(H); if (p != NULL) printf("\nTHE EXTRACTED NODE IS %d", p->n); printf("\nNOW THE HEAP IS:\n"); DISPLAY(H); printf("\nEXTRACT MORE(y/Y)\n"); fflush(stdin); scanf("%c", &ch); } while (ch == 'Y' || ch == 'y'); break; case 3: do { printf("\nENTER THE KEY OF THE NODE TO BE DECREASED:"); scanf("%d", &m); printf("\nENTER THE NEW KEY : "); scanf("%d", &l); bin_HEAP_DECREASE_KEY(H, m, l); printf("\nNOW THE HEAP IS:\n"); DISPLAY(H); printf("\nDECREASE MORE(y/Y)\n"); fflush(stdin); scanf("%c", &ch); } while (ch == 'Y' || ch == 'y'); break; case 4: do { printf("\nENTER THE KEY TO BE DELETED: "); scanf("%d", &m); bin_HEAP_DELETE(H, m); printf("\nDELETE MORE(y/Y)\n"); fflush(stdin); scanf("%c", &ch); } while (ch == 'y' || ch == 'Y'); break; case 5: printf("\nTHANK U SIR\n"); break; default: printf("\nINVALID ENTRY...TRY AGAIN....\n"); } } while (l != 5); }
code/data_structures/src/tree/heap/binomial_heap/binomial_heap.cpp
#include <iostream> #include <queue> #include <vector> /* Part of Cosmos by OpenGenus Foundation */ using namespace std; class Node { public: int value; int degree; Node* parent; Node* child; Node* sibling; Node() : value(0), degree(0), parent(0), child(0), sibling(0) { }; ~Node() { }; }; class BinomialHeap { public: BinomialHeap() : head(NULL) { } Node* getHead() { return head; } void insert(int value) { BinomialHeap tempHeap; Node* tempNode = new Node(); tempNode->value = value; tempHeap.setHead(&tempNode); bHeapUnion(tempHeap); } void deleteMin() { int min = head->value; Node* tmp = head; Node* minPre = NULL; Node* minCurr = head; //find the root x with the minimum key in the root list of H // remove x from the root list of H while (tmp->sibling) { if (tmp->sibling->value < min) { min = tmp->sibling->value; minPre = tmp; minCurr = tmp->sibling; } tmp = tmp->sibling; } if (!minPre && minCurr) head = minCurr->sibling; else if (minPre && minCurr) minPre->sibling = minCurr->sibling; //H' Make-BINOMIAL-HEAP() BinomialHeap bh; Node *pre, *curr; //reverse the order of the linked list of x's children pre = tmp = NULL; curr = minCurr->child; while (curr) { tmp = curr->sibling; curr->sibling = pre; curr->parent = NULL; pre = curr; curr = tmp; } //set head[H'] to point to the head of the resulting list bh.setHead(&pre); //H <- BINOMIAL-HEAP-UNION bHeapUnion(bh); } int getMin() { int min = 2 << 20; Node* tmp = head; while (tmp) { if (tmp->value < min) min = tmp->value; tmp = tmp->sibling; } return min; } void preorder() { puts(""); Node* tmp = head; while (tmp) { _preorder(tmp); tmp = tmp->sibling; } puts(""); } void BFS() { puts(""); queue<Node*> nodeQueue; Node *tmp = head; while (tmp) { nodeQueue.push(tmp); tmp = tmp->sibling; } while (!nodeQueue.empty()) { Node *node = nodeQueue.front(); nodeQueue.pop(); if (node) printf("%d ", node->value); node = node->child; while (node) { nodeQueue.push(node); node = node->sibling; } } puts(""); } void bHeapUnion(BinomialHeap &bh) { _mergeHeap(bh); Node* prev = NULL; Node* x = head; Node* next = x->sibling; while (next) { if (x->degree != next->degree) { prev = x; //Case 1 and 2 x = next; //Case 1 and 2 } else if (next->sibling && next->sibling->degree == x->degree) //three BT has the same degree { if (next->value < x->value && next->value < next->sibling->value) //312, need to trans to 132 { x->sibling = next->sibling; next->sibling = x; if (prev) prev->sibling = next; else head = next; prev = x; x = next; } else if (next->sibling->value < x->value && next->sibling->value < next->value) //321, need to trans to 123 { x->sibling = next->sibling->sibling; next->sibling->sibling = next; if (prev) prev->sibling = next->sibling; else head = next->sibling; prev = next->sibling; next->sibling = x; x = next; } else { prev = x; //Case 1 and 2 x = next; //Case 1 and 2 } } else if (x->value <= next->value) { x->sibling = next->sibling; //Case 3 _mergeTree(next, x); //Case 3 next = x; } else { if (!prev) //Case 4 head = next; //Case 4 else prev->sibling = next; //Case 4 _mergeTree(x, next); //Case 4 x = next; //Case 4 } next = next->sibling; //Case 4 } } int size() { return _size(head); } void setHead(Node** node) { head = *node; } private: int _size(Node* node) { if (!node) return 0; return 1 + _size(node->child) + _size(node->sibling); } void _preorder(Node* node) { if (!node) return; printf("%d ", node->value); _preorder(node->child); if (node->parent) _preorder(node->sibling); //printf("%d(%d) ",node->value,node->degree); } void _mergeTree(Node* tree1, Node* tree2) { tree1->parent = tree2; tree1->sibling = tree2->child; tree2->child = tree1; tree2->degree++; } void _mergeHeap(BinomialHeap &bh) { Node* head2 = bh.getHead(); Node* head1 = head; //for new pointer Node *newHead, *newCurr; if (!head1) { head = head2; return; } if (head1->degree > head2->degree) { newHead = newCurr = head2; head2 = head2->sibling; } else { newHead = newCurr = head1; head1 = head1->sibling; } //Sorted by degree into monotonically increasing order while (head1 && head2) { if (head1->degree < head2->degree) { newCurr->sibling = head1; newCurr = head1; head1 = head1->sibling; } else { newCurr->sibling = head2; newCurr = head2; head2 = head2->sibling; } } while (head1) { newCurr->sibling = head1; newCurr = head1; head1 = head1->sibling; } while (head2) { newCurr->sibling = head2; newCurr = head2; head2 = head2->sibling; } head = newHead; } Node* head; }; int main() { vector<int> heap1{5, 4, 3, 2, 1}; vector<int> heap2{4, 3, 2, 1, 8}; BinomialHeap bh1, bh2; for (auto v: heap1) bh1.insert(v); for (auto v: heap2) bh2.insert(v); printf("preorder traversal of first binomialheap: "); bh1.preorder(); printf("BFS of first binomialheap: "); bh1.BFS(); printf("\n"); printf("preorder traversal of second binomialheap: "); bh2.preorder(); printf("BFS of second binomialheap: "); bh2.BFS(); printf("-----------Union------------------\n");; bh1.bHeapUnion(bh2); printf("preorder traversal of union: "); bh1.preorder(); printf("BFS of union: "); bh1.BFS(); printf("-----------Delete min = 1 --------\n"); bh1.deleteMin(); printf("preorder traversal of delete min: "); bh1.preorder(); printf("BFS of union: "); bh1.BFS(); printf("-----------Delete min = 2 --------\n"); bh1.deleteMin(); printf("preorder traversal of delete min: "); bh1.preorder(); printf("BFS of union: "); bh1.BFS(); printf("binomialheap min:%d\n", bh1.getMin()); printf("binomailheap size %d\n", bh1.size()); }
code/data_structures/src/tree/heap/binomial_heap/binomial_heap.scala
object BinomialHeap { def apply[T](value: T)(implicit ord: Ordering[T], treeOrd: Ordering[BinTree[T]]) = new BinomialHeap(Map())(ord, treeOrd).add(BinTree(value)) } case class BinomialHeap[T](heap: Map[Int, BinTree[T]])(implicit ord: Ordering[T], treeOrd: Ordering[BinTree[T]]) { def add(tree: BinTree[T]): BinomialHeap[T] = { if (heap.contains(tree.order)) { BinomialHeap(heap - tree.order).add(tree.merge(heap(tree.order))) } else { BinomialHeap(heap + (tree.order -> tree)) } } def add(value: T): BinomialHeap[T] = add(BinTree(value)) def min(): T = heap.valuesIterator.min.value def deleteMin(): BinomialHeap[T] = { val minTree = heap.valuesIterator.min if (minTree.order == 0) { BinomialHeap(heap - minTree.order) } else { val remainingHeap = BinomialHeap(heap - minTree.order) minTree.kids.foldLeft(remainingHeap) { case (acc: BinomialHeap[T], tree: BinTree[T]) => acc.add(tree) } } } } object BinTree { def apply[T](value: T)(implicit ord: Ordering[T]) = new BinTree(value, 0, IndexedSeq()) } case class BinTree[T](value: T, order: Int, kids: IndexedSeq[BinTree[T]])(implicit ord: Ordering[T]) { def merge(other: BinTree[T]): BinTree[T] = { assert(other.order == order) if (ord.lt(other.value, value)) { BinTree(other.value, order + 1, other.kids :+ this) } else { BinTree(value, order + 1, kids :+ other) } } } object Main { def main(args: Array[String]): Unit = { implicit val ord = Ordering.by[BinTree[Int], Int](_.value) println(BinomialHeap(10).add(-5)) println(BinomialHeap(10).add(-5).add(3)) println(BinomialHeap(10).add(-5).add(3).add(13)) println(BinomialHeap(10).add(-5).add(3).add(13).min) println(BinomialHeap(10).add(-5).add(3).add(13).deleteMin()) } }
code/data_structures/src/tree/heap/max_heap/max_heap.c
/* Part of Cosmos by OpenGenus Foundation This is a C program that forms a max heap. The following queries can be used: 0 - Print the max-heap 1 - Heapsort, then print the sorted array 2 [element] - Insert element into max-heap, then print the heap 3 - Remove/extract maximum element in max-heap, then print the heap 4 - Print maximum element of max-heap */ # include <stdio.h> int n = 0; // global variable for maintaining the sixe of the heap int size = 0; // global array used for heapsort /* The function down() is used for building the heap and for deleting the maximum element from the heap The parameters are: 1. pos - index of the element to be inserted 2. val - value to be compared with 3. heap - the heap array */ int down(int pos, int val, int heap[n]) { int target = 0; while(2*pos<=n) { int left = 2*pos; int right = left + 1; if(right<=n && heap[right]>heap[left]) { target = right; } else { target = left; } if(heap[target]>val) { heap[pos] = heap[target]; pos = target; } else { break; } } return pos; } /* The function down2() is used for heapsort's delete functinality The parameters are: 1. pos - index of the element to be inserted 2. val - value to be compared with 3. heap - the heap array */ int down2(int pos, int val, int heap[size]) { int target = 0; while(2*pos<=size) { int left = 2*pos; int right = left + 1; if(right<=size && heap[right]>heap[left]) { target = right; } else { target = left; } if(heap[target]>val) { heap[pos] = heap[target]; pos = target; } else { break; } } return pos; } /* The function buildheap() is used for constructing the max heap which uses the percolatedown method The parameters are: 1. heap - the heap array */ void builheap(int heap[n]) { for(int i = n/2 ; i>0 ; i--) { int node = heap[i]; int position = percolatedown(i, heap[i], heap); heap[position] = node; } } /* The function printheap() is used for printing the max heap The parameters are: 1. heap - the heap array */ void printheap(int heap[n]) { for(int i = 1 ; i<=n ; i++) { printf("%d ", heap[i]); } } /* The function deletemax is used for deleting the maximum element from the heap The parameters are: 1. heap - the heap array */ void deletemax(int heap[n]) { int newpos = down(1, heap[n+1], heap); heap[newpos] = heap[n+1]; } /* The function deletemax2 is used for deleting the maximum element from the heap The parameters are: 1. heap - the heap array */ void deletemax2(int heap[size]) { int newpos = down2(1, heap[size+1], heap); heap[newpos] = heap[size+1]; } /* The function heapsort() is used for sorting the heap array The parameters are: 1. heap - the heap array 2. arr - it stores the sorted elements of the heap */ void heapsort(int heap[n+1], int arr[n+1]) { size = n; int heapsortarr[100]; for(int i = 1 ; i<=n ; i++) { heapsortarr[i] = heap[i]; } for(int i = 1 ; i<=n ; i++) { arr[n-i+1] = heapsortarr[1]; size--; deletemax2(heapsortarr); } } int main() { scanf("%d", &n); int heaparr[100]; for(int i = 0 ; i<n ; i++) { scanf("%d", &heaparr[i+1]); } builheap(heaparr); int t = 0; scanf("%d", &t); for(int j = 0 ; j<t ; j++) { int q = 0; scanf("%d", &q); if(q==0) // Print the max-heap { printheap(heaparr); printf("\n"); } else if(q==1) // Heapsort, then print the sorted array { int arr[n+1]; heapsort(heaparr, arr); printheap(arr); printf("\n"); } else if(q==2) // Insert element into max-heap, then print the heap { int a = 0; scanf("%d", &a); n++; heaparr[n] = a; builheap(heaparr); printheap(heaparr); printf("\n"); } else if(q==3) // Remove/extract maximum element in max-heap, then print the heap { n--; deletemax(heaparr); printheap(heaparr); printf("\n"); } else if(q==4) // Print maximum element of max-heap { printf("%d\n", heaparr[1]); } } }
code/data_structures/src/tree/heap/max_heap/max_heap.go
/* Part of Cosmos by OpenGenus Foundation */ package main import "fmt" type MaxHeap struct { data []int } func swap(x, y int) (int, int) { return y, x } func (h *MaxHeap) Push(value int) { h.data = append(h.data, value) index := len(h.data) - 1 parent := (index - 1) / 2 for index > 0 && h.data[index] > h.data[parent] { h.data[index], h.data[parent] = swap(h.data[index], h.data[parent]) index = parent parent = (index - 1) / 2 } } func (h *MaxHeap) Top() int { return h.data[0] } func (h *MaxHeap) ExtractTop() int { index := len(h.data) - 1 max := h.Top() h.data[0], h.data[index] = swap(h.data[0], h.data[index]) h.data = h.data[:index] h.heapify(0) return max } func (h *MaxHeap) Pop() { index := len(h.data) - 1 h.data[0], h.data[index] = swap(h.data[0], h.data[index]) h.data = h.data[:index] h.heapify(0) } func (h *MaxHeap) heapify(index int) { left := (index * 2) + 1 right := left + 1 target := index if left < len(h.data) && h.data[left] > h.data[index] { target = left } if right < len(h.data) && h.data[right] > h.data[target] { target = right } if target != index { h.data[index], h.data[target] = swap(h.data[index], h.data[target]) h.heapify(target) } } func (h *MaxHeap) Empty() bool { return len(h.data) == 0 } func main() { data := []int{45, 6, 4, 3, 2, 72, 34, 12, 456, 29, 312} var h MaxHeap for _, v := range data { h.Push(v) } fmt.Println("Current Data is ", h.data) for !h.Empty() { fmt.Println(h.Top()) h.Pop() } }
code/data_structures/src/tree/heap/max_heap/max_heap.java
//Part of Open Genus foundation import java.util.Scanner; /** * Created by risha on 15-10-2017. */ // Priority Queue binary max_heap implementation public class MaxPQ<Key extends Comparable<Key>> { private Key []pq; private int N=0; private int capacity; public MaxPQ(int capacity) { pq= (Key[]) new Comparable[capacity+1]; this.capacity=capacity; } public boolean isEmpty() { return N==0; } public void insertKey(Key x) { if (N+1>capacity) resize(); pq[++N]=x; swim(N); } public int size() { return N; } /* public int getCapacity() { return this.capacity; }*/ private void resize() { this.capacity=2*N; Key[] temp= (Key[]) new Comparable[this.capacity+1]; for (int i=1;i<=N;i++) temp[i]=pq[i]; pq=temp; } public Key delMax() { if (isEmpty()) return null; Key max=pq[1]; exch(1,N--); sink(1); pq[N+1]=null; return max; } private void swim(int k) { while (k>1 && less(k/2,k)) { exch(k,k/2); k=k/2; } } private void sink(int k) { while (2*k<=N) { int j=2*k; if(j<N && less(j,j+1))j++; if (!less(k,j))break; exch(k,j); k=j; } } private boolean less(int i,int j) { return pq[i].compareTo(pq[j])<0; } private void exch(int i,int j) { Key t=pq[i]; pq[i]=pq[j]; pq[j]=t; } public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Enter the size of heap"); int n=sc.nextInt(); MaxPQ<Integer> pq=new MaxPQ<Integer>(n); for (int i=0;i<n;i++) pq.insertKey(sc.nextInt()); System.out.println("Size of heap: "+pq.size()); // System.out.println("Capacity: "+pq.getCapacity()); System.out.println("Maximum keys in order"); while (!pq.isEmpty()) { System.out.println(pq.delMax()); } System.out.println(pq.delMax()); } }
code/data_structures/src/tree/heap/max_heap/max_heap.py
# Part of Cosmos by OpenGenus Foundation def left(i): return 2 * i + 1 def right(i): return 2 * i + 2 def heapify(a, i): l = left(i) r = right(i) length = len(a) if l < length and a[l] > a[i]: largest = l else: largest = i if r < length and a[r] > a[largest]: largest = r if largest != i: a[i], a[largest] = a[largest], a[i] heapify(a, largest) def build_max_heap(a): for i in range((len(list(a)) - 1) // 2, -1, -1): heapify(a, i) if __name__ == "__main__": print("Enter the array of which you want to create a max heap") a = [int(x) for x in input().split()] build_max_heap(a) print("The max heap is - ") for i in range(len(a)): print(a[i], end=" ") print("")
code/data_structures/src/tree/heap/min_heap/min_heap.c
#include <stdio.h> #define asize 100 #define min(a, b) (((a) < (b)) ? (a) : (b)) struct heap { int a[asize]; int hsize ; } H; void swap(int *a, int *b) { int temp = *b; *b = *a; *a = temp; } void heapInsert(int key) { ++H.hsize; H.a[H.hsize] = key; int i = H.hsize; while (i > 1 && H.a[i] < H.a[i / 2]) { swap(&H.a[i], &H.a[i / 2]); i = i / 2; } printf("%d is inserted in Min Heap \n", key); } void displayHeap() { int i; printf("Elements in the heap:- \n"); for (i = 1; i <= H.hsize; i++) printf("%d ", H.a[i]); printf("\n"); } void delMin() { if (H.hsize == 0) { printf("Heap is empty,No element can be popped out \n"); return; } int x = H.a[1]; H.a[1] = H.a[H.hsize]; --H.hsize; int i = 1; while ((2 * i) <= H.hsize) { if ((2 * i) + 1 <= H.hsize && H.a[i] > min(H.a[2 * i], H.a[(2 * i) + 1])) { if (H.a[(2 * i) + 1] < H.a[2 * i]) { swap(&H.a[i], &H.a[(2 * i) + 1]); i=(2 * i) + 1; } else { swap(&H.a[i], &H.a[(2 * i)]); i=2 * i; } } else if ((2 * i) + 1 > H.hsize && H.a[i] > H.a[2 * i]) { swap(&H.a[i], &H.a[(2 * i)]); break; } else break; } printf("%d is popped out \n", x); } int main() { int key, ch; H.hsize = 0; while (1) { printf("1.Insert\n2.Display Min Heap\n3.Pop out Minimum element\n4.Exit\n"); scanf("%d", &ch); switch (ch) { case 1 : printf("Enter integer to be inserted \n"); scanf("%d", &key); heapInsert(key); break; case 2 : displayHeap(); break; case 3 : delMin(); break; case 4 : return (0); } } }
code/data_structures/src/tree/heap/min_heap/min_heap.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> using namespace std; class minHeap { vector<int> v; void heapify(size_t i) { size_t l = 2 * i; size_t r = 2 * i + 1; size_t min = i; if (l < v.size() && v[l] < v[min]) min = l; if (r < v.size() && v[r] < v[min]) min = r; if (min != i) { swap(v[i], v[min]); heapify(min); } } public: minHeap() { v.push_back(-1); } void insert(int data) { v.push_back(data); int i = v.size() - 1; int parent = i / 2; while (v[i] < v[parent] && i > 1) { swap(v[i], v[parent]); i = parent; parent = parent / 2; } } int top() { return v[1]; } void pop() { int last = v.size() - 1; swap(v[1], v[last]); v.pop_back(); heapify(1); } bool isEmpty() { return v.size() == 1; } }; int main() { int data; cout << "\nEnter data : "; cin >> data; minHeap h; while (data != -1) { h.insert(data); cout << "\nEnter data(-1 to exit) : "; cin >> data; } while (!h.isEmpty()) { cout << h.top() << " "; h.pop(); } return 0; }
code/data_structures/src/tree/heap/min_heap/min_heap.java
/* Part of Cosmos by OpenGenus Foundation */ public class MinHeap { private int[] Heap; private int size; private int maxsize; private static final int FRONT = 1; public MinHeap(int maxsize) { this.maxsize = maxsize; this.size = 0; Heap = new int[this.maxsize + 1]; Heap[0] = Integer.MIN_VALUE; } private int parent(int pos) { return pos / 2; } private int leftChild(int pos) { return (2 * pos); } private int rightChild(int pos) { return (2 * pos) + 1; } private boolean isLeaf(int pos) { if (pos >= (size / 2) && pos <= size) { return true; } return false; } private void swap(int fpos, int spos) { int tmp; tmp = Heap[fpos]; Heap[fpos] = Heap[spos]; Heap[spos] = tmp; } private void heapify(int pos) { if (!isLeaf(pos)) { if ( Heap[pos] > Heap[leftChild(pos)] || Heap[pos] > Heap[rightChild(pos)]) { if (Heap[leftChild(pos)] < Heap[rightChild(pos)]) { swap(pos, leftChild(pos)); heapify(leftChild(pos)); }else { swap(pos, rightChild(pos)); heapify(rightChild(pos)); } } } } public void insert(int element) { Heap[++size] = element; int current = size; while (Heap[current] < Heap[parent(current)]) { swap(current,parent(current)); current = parent(current); } } public void print() { for (int i = 1; i <= size / 2; i++ ) { System.out.print(" PARENT : " + Heap[i] + " LEFT CHILD : " + Heap[2*i] + " RIGHT CHILD :" + Heap[2 * i + 1]); System.out.println(); } } public void minHeap() { for (int pos = (size / 2); pos >= 1 ; pos--) { heapify(pos); } } public int remove() { int popped = Heap[FRONT]; Heap[FRONT] = Heap[size--]; heapify(FRONT); return popped; } public static void main(String...arg) { System.out.println("The Min Heap is "); MinHeap minHeap = new MinHeap(15); minHeap.insert(5); minHeap.insert(3); minHeap.insert(17); minHeap.insert(10); minHeap.insert(84); minHeap.insert(19); minHeap.insert(6); minHeap.insert(22); minHeap.insert(9); minHeap.minHeap(); minHeap.print(); System.out.println("The Min val is " + minHeap.remove()); } }
code/data_structures/src/tree/heap/min_heap/min_heap.js
/** Source: https://github.com/brunocalou/graph-theory-js/blob/master/src/data_structures/binary_heap.js */ "use strict"; /** * The function to use when comparing variables * @typedef {function} comparatorFunction * @param {any} a - The first element to compare * @param {any} b - The second element to compare * @returns {number} A negative number, zero, or a positive number * as the first argument is less than, equal to, or greater than the second */ /** * Comparator class * @constructor * @classdesc The Comparator class is a helper class that compares two variables * according to a comparator function. * @param {comparatorFunction} fn - The comparator function */ function Comparator(compareFn) { if (compareFn) { /**@type {comparatorFunction} */ this.compare = compareFn; } } /** * Default comparator function * @param {any} a - The first element to compare * @param {any} b - The second element to compare * @returns {number} A negative number, zero, or a positive number * as the first argument is less than, equal to, or greater than the second * @see comparatorFunction */ Comparator.prototype.compare = function(a, b) { if (a === b) return 0; return a < b ? -1 : 1; }; /** * Compare if the first element is equal to the second one. * Override this method if you are comparing arrays, objects, ... * @example * function compare (a,b) { * return a[0] - b[0]; * } * var a = [1,2]; * var b = [1,2]; * * var comparator = new Comparator(compare); * * //Compare just the values * comparator.equal(a,b);//true * * comparator.equal = function(a,b) { * return a == b; * } * * //Compare the refecence too * comparator.equal(a,b);//false * * var c = a; * comparator.equal(a,c);//true * * @param {any} a - The first element to compare * @param {any} b - The second element to compare * @returns {boolean} True if the first element is equal to * the second one, false otherwise */ Comparator.prototype.equal = function(a, b) { return this.compare(a, b) === 0; }; /** * Compare if the first element is less than the second one * @param {any} a - The first element to compare * @param {any} b - The second element to compare * @returns {boolean} True if the first element is less than * the second one, false otherwise */ Comparator.prototype.lessThan = function(a, b) { return this.compare(a, b) < 0; }; /** * Compare if the first element is less than or equal the second one * @param {any} a - The first element to compare * @param {any} b - The second element to compare * @returns {boolean} True if the first element is less than or equal * the second one, false otherwise */ Comparator.prototype.lessThanOrEqual = function(a, b) { return this.compare(a, b) < 0 || this.equal(a, b); }; /** * Compare if the first element is greater than the second one * @param {any} a - The first element to compare * @param {any} b - The second element to compare * @returns {boolean} True if the first element is greater than * the second one, false otherwise */ Comparator.prototype.greaterThan = function(a, b) { return this.compare(a, b) > 0; }; /** * Compare if the first element is greater than or equal the second one * @param {any} a - The first element to compare * @param {any} b - The second element to compare * @returns {boolean} True if the first element is greater than or equal * the second one, false otherwise */ Comparator.prototype.greaterThanOrEqual = function(a, b) { return this.compare(a, b) > 0 || this.equal(a, b); }; /** * Change the compare function to return the opposite results * @example * // false * Comparator.greaterThan(1, 2); * @example * // true * Comparator.invert(); * Comparator.greaterThan(1, 2); */ Comparator.prototype.invert = function() { this._originalCompare = this.compare; this.compare = function(a, b) { return this._originalCompare(b, a); }.bind(this); }; /** * Min Binary Heap Class * @constructor * @classdesc The MinBinaryHeap class implements a minimum binary heap data structure * @param {function} comparator_fn - The comparator function */ function MinBinaryHeap(comparator_fn) { /**@private * @type {array} */ this._elements = [null]; // will not use the first index /**@public * @type {Comparator} */ this.comparator = new Comparator(comparator_fn); /**@private * @type {number} */ this._length = 0; Object.defineProperty(this, "length", { get: function() { return this._length; } }); } /** * Changes the value of the element * @param {any} old_element - The element to be replaced * @param {any} new_element - The new element */ MinBinaryHeap.prototype.changeElement = function(old_element, new_element) { for (var i = 1; i <= this._length; i += 1) { if (this.comparator.equal(old_element, this._elements[i])) { this._elements[i] = new_element; break; } } this._elements.shift(); //Removes the null from the first index this.heapify(this._elements); }; /** * Removes all the elements in the heap */ MinBinaryHeap.prototype.clear = function() { this._elements.length = 0; this._elements[0] = null; this._length = 0; }; /** * The function called by the forEach method. * @callback MinBinaryHeap~iterateCallback * @function * @param {any} element - The current element * @param {number} [index] - The index of the current element * @param {MinBinaryHeap} [binary_heap] - The binary heap it is using */ /** * Performs the fn function for all the elements of the heap, untill the callback function returns false * @param {iterateCallback} fn - The function the be executed on each element * @param {object} [this_arg] - The object to use as this when calling the fn function */ MinBinaryHeap.prototype.every = function(fn, this_arg) { var ordered_array = this.toArray(); var index = 0; while (ordered_array[0] !== undefined) { if (!fn.call(this_arg, ordered_array.shift(), index, this)) { break; } index += 1; } }; /** * Performs the fn function for all the elements of the list * @param {iterateCallback} fn - The function the be executed on each element * @param {object} [this_arg] - The object to use as this when calling the fn function */ MinBinaryHeap.prototype.forEach = function(fn, this_arg) { var ordered_array = this.toArray(); var index = 0; while (ordered_array[0] !== undefined) { fn.call(this_arg, ordered_array.shift(), index, this); index += 1; } }; /** * Transforms an array into a binary heap * @param {array} array - The array to transform */ MinBinaryHeap.prototype.heapify = function(array) { this._length = array.length; this._elements = array; this._elements.unshift(null); for (var i = Math.floor(this._length / 2); i >= 1; i -= 1) { this._shiftDown(i); } }; /** * Inserts the element to the heap * @param {any} element - The element to be inserted */ MinBinaryHeap.prototype.insert = function(element) { this._elements.push(element); this._shiftUp(); this._length += 1; }; /** * Returns if the heap is empty * @returns If the heap is empty */ MinBinaryHeap.prototype.isEmpty = function() { return !this._length; }; /** * Returns the first element without removing it * @returns The first element without removing it */ MinBinaryHeap.prototype.peek = function() { return this._elements[1]; }; /** * Inserts the element to the heap * This method is equivalent to insert * @see insert */ MinBinaryHeap.prototype.push = function(element) { this.insert(element); }; /** * Returns the first element while removing it * @returns {any} The first element while removing it, undefined if the heap is empty */ MinBinaryHeap.prototype.pop = function() { var removed_element = this._elements[1]; if (this._length === 1) { this._elements.pop(); this._length -= 1; } else if (this._length > 1) { this._elements[1] = this._elements.pop(); this._length -= 1; this._shiftDown(); } return removed_element; }; /** * Shifts the index to a correct position below * @param {number} index - The index to shift down */ MinBinaryHeap.prototype._shiftDown = function(index) { if (index === undefined) index = 1; var parent_index = index; var left_child_index = parent_index * 2; var right_child_index = parent_index * 2 + 1; var smallest_child_index; var array_length = this._length + 1; while ( parent_index < array_length && (left_child_index < array_length || right_child_index < array_length) ) { if (right_child_index < array_length) { if (left_child_index < array_length) { if ( this.comparator.lessThan( this._elements[left_child_index], this._elements[right_child_index] ) ) { smallest_child_index = left_child_index; } else { smallest_child_index = right_child_index; } } } else { if (left_child_index < array_length) { smallest_child_index = left_child_index; } } if ( this.comparator.greaterThan( this._elements[parent_index], this._elements[smallest_child_index] ) ) { this._swap(parent_index, smallest_child_index); } parent_index = smallest_child_index; left_child_index = parent_index * 2; right_child_index = parent_index * 2 + 1; } }; /** * Shifts the index to a correct position above * @param {number} index - The index to shift up */ MinBinaryHeap.prototype._shiftUp = function(index) { if (index === undefined) index = this._elements.length - 1; var child_index = index; var parent_index = Math.floor(child_index / 2); while ( child_index > 1 && this.comparator.greaterThan( this._elements[parent_index], this._elements[child_index] ) ) { this._swap(parent_index, child_index); child_index = parent_index; parent_index = Math.floor(child_index / 2); } }; /** * Returns the size of the heap * @returns {number} The size of the heap */ MinBinaryHeap.prototype.size = function() { return this._length; }; /** * Swaps two elements * @private * @param {number} a - The index of the first element * @param {number} b - The index of the second element */ MinBinaryHeap.prototype._swap = function(a, b) { var aux = this._elements[a]; this._elements[a] = this._elements[b]; this._elements[b] = aux; }; /** * Converts the heap to an ordered array, without changing the heap. * Note that if the heap contains objects, the generated array will * contain references to the same objects * @returns {array} The converted heap in an ordered array format */ MinBinaryHeap.prototype.toArray = function() { var array = []; var min_binary_heap = new MinBinaryHeap(this.comparator.compare); min_binary_heap._elements = this._elements.slice(); min_binary_heap._length = this._length; while (min_binary_heap.peek() !== undefined) { array.push(min_binary_heap.pop()); } return array; }; /** * Max Binary Heap Class * @constructor * @extends MinBinaryHeap */ function MaxBinaryHeap(comparator) { MinBinaryHeap.call(this, comparator); this.comparator.invert(); } MaxBinaryHeap.prototype.toArray = function() { var array = []; var max_binary_heap = new MaxBinaryHeap(); max_binary_heap._elements = this._elements.slice(); max_binary_heap._length = this._length; max_binary_heap._comparator = this.comparator; while (max_binary_heap.peek() !== undefined) { array.push(max_binary_heap.pop()); } return array; }; /** * Performs an OOP like inheritance * @param {function} parent - The parent class * @param {function} child - The child class */ function inherit(parent, child) { var parent_copy = Object.create(parent.prototype); child.prototype = parent_copy; child.prototype.constructor = child; } inherit(MinBinaryHeap, MaxBinaryHeap); module.exports = { MinBinaryHeap: MinBinaryHeap, MaxBinaryHeap: MaxBinaryHeap, Comparator: Comparator };
code/data_structures/src/tree/heap/min_heap/min_heap.py
# Part of Cosmos by OpenGenus Foundation def left(i): return 2 * i + 1 def right(i): return 2 * i + 2 def heapify(a, i): l = left(i) r = right(i) if l < len(a) and a[l] < a[i]: smallest = l else: smallest = i if r < len(a) and a[r] < a[smallest]: smallest = r if smallest != i: a[i], a[smallest] = a[smallest], a[i] heapify(a, smallest) def build_min_heap(a): for i in range((len(a) - 1) // 2, -1, -1): heapify(a, i) if __name__ == "__main__": print("Enter the array of which you want to create a min heap") a = [int(x) for x in input().split()] build_min_heap(a) print("The min heap is -") for i in a: print(i, end=" ") print("")
code/data_structures/src/tree/heap/min_heap/min_heap.rb
# Part of Cosmos by OpenGenus Foundation class MinHeap attr_reader :heap def initialize @heap = [] end def push(value) @heap.push(value) index = @heap.size - 1 up_heap(index) end def pop min = @heap.first last = @heap.pop @heap[0] = last heapify(0) min end def empty? heap.empty? end def min @heap.first end private def up_heap(index) parent_index = index / 2 if @heap[parent_index] > @heap[index] parent = @heap[parent_index] @heap[parent_index] = @heap[index] @heap[index] = parent up_heap(parent_index) end end def heapify(index) left = index * 2 right = left + 1 min = index min = left if left < @heap.size && @heap[left] < @heap[min] min = right if right < @heap.size && @heap[right] < @heap[min] if min != index min_value = @heap[min] @heap[min] = @heap[index] @heap[index] = min_value heapify(min) end end end h = MinHeap.new h.push(4) h.push(10) h.push(2) p h.min h.push(5) p h.pop p h.min h.push(9) h.push(1) p h.min
code/data_structures/src/tree/heap/min_heap/min_heap.swift
public func pushHeap<T>(inout xs: [T], value: T, compare: (T, T) -> Bool) { xs.append(value) siftUp(&xs, xs.startIndex, xs.endIndex, compare, xs.count) } public func pushHeap<T: Comparable>(inout xs: [T], value: T) { pushHeap(&xs, value) {a, b in a < b} } public func popHeap<T>(inout xs: [T], comp: (T, T) -> Bool) -> T { precondition(!xs.isEmpty, "cannot pop an empty heap") swap(&xs[0], &xs[xs.endIndex - 1]) siftDown(&xs, xs.startIndex, xs.endIndex, comp, xs.count - 1, xs.startIndex) let result = xs.removeLast() return result } public func popHeap<T: Comparable>(inout xs: [T]) -> T { return popHeap(&xs) {a, b in a < b} } // MARK: - Private func siftDown<T>(inout xs: [T], var first: Int, var last: Int, compare: (T, T) -> Bool, var len: Int, var start: Int) { // left-child of start is at 2 * start + 1 // right-child of start is at 2 * start + 2 var child = start - first if (len < 2 || (len - 2) / 2 < child) { return } child = 2 * child + 1; var child_i = first + child if child + 1 < len && compare(xs[child_i + 1], xs[child_i]) { // right-child exists and is greater than left-child ++child_i ++child } // check if we are in heap-order if compare(xs[start], xs[child_i]) { // we are, start is larger than it's largest child return } let top = xs[start] do { // we are not in heap-order, swap the parent with it's largest child xs[start] = xs[child_i] start = child_i; if ((len - 2) / 2 < child) { break } // recompute the child based off of the updated parent child = 2 * child + 1 child_i = first + child if child + 1 < len && compare(xs[child_i + 1], xs[child_i]) { // right-child exists and is greater than left-child ++child_i ++child } // check if we are in heap-order } while (!compare(top, xs[child_i])) xs[start] = top } private func siftUp<T>(inout xs: [T], var first: Int, var last: Int, compare: (T, T) -> Bool, var len: Int) { if len <= 1 { return } len = (len - 2) / 2 var index = first + len last -= 1 if (compare(xs[last], xs[index])) { let t = xs[last] do { xs[last] = xs[index] last = index if len == 0 { break } len = (len - 1) / 2 index = first + len } while (compare(t, xs[index])) xs[last] = t } }
code/data_structures/src/tree/heap/pairing_heap/README.md
# Pairing heap A pairing heap is a heap structure, which is simple to implement in functional languages, and which provides good amortized performance. ## Operations - merge - &Theta;(1) - Merges two heaps - insert - &Theta;(1) - Inserts an element into a heap - findMin - &Theta;(1) - Returns the minimal element from the heap - deleteMin - O(log n) - Deletes the minimal element from the heap ## Further information - [Wikipedia](https://en.wikipedia.org/wiki/Pairing_heap) --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/data_structures/src/tree/heap/pairing_heap/pairing_heap.fs
module PairHeap type Heap<'a> = | Empty | Heap of 'a * (Heap<'a> list) let findMin = function | Empty -> failwith "empty" | Heap (c, _) -> c let merge heap1 heap2 = match heap1, heap2 with | Empty, _ -> heap2 | _, Empty -> heap1 | Heap (c1, sub1), Heap (c2, sub2) -> if c1 > c2 then Heap (c1, heap2::sub1) else Heap (c2, heap1::sub2) let insert c heap = merge (Heap (c, [])) heap let rec mergePairs = function | [] -> Empty | [sub] -> sub | sub1::sub2::rest -> merge (merge sub1 sub2) (mergePairs rest) let deleteMin = function | Empty -> failwith "empty" | Heap (_, sub) -> mergePairs sub
code/data_structures/src/tree/heap/pairing_heap/pairing_heap.sml
(* Pairing heap - http://en.wikipedia.org/wiki/Pairing_heap *) (* Part of Cosmos by OpenGenus Foundation *) functor PairingHeap(type t val cmp : t * t -> order) = struct datatype 'a heap = Empty | Heap of 'a * 'a heap list; (* merge, O(1) * Merges two heaps *) fun merge (Empty, h) = h | merge (h, Empty) = h | merge (h1 as Heap(e1, s1), h2 as Heap(e2, s2)) = case cmp (e1, e2) of LESS => Heap(e1, h2 :: s1) | _ => Heap(e2, h1 :: s2) (* insert, O(1) * Inserts an element into the heap *) fun insert (e, h) = merge (Heap (e, []), h) (* findMin, O(1) * Returns the smallest element of the heap *) fun findMin Empty = raise Domain | findMin (Heap(e, _)) = e (* deleteMin, O(lg n) amortized * Deletes the smallest element of the heap *) local fun mergePairs [] = Empty | mergePairs [h] = h | mergePairs (h1::h2::hs) = merge (merge(h1, h2), mergePairs hs) in fun deleteMin Empty = raise Domain | deleteMin (Heap(_, s)) = mergePairs s end (* build, O(n) * Builds a heap from a list *) fun build es = foldl insert Empty es; end local structure IntHeap = PairingHeap(type t = int; val cmp = Int.compare); open IntHeap fun heapsort' Empty = [] | heapsort' h = findMin h :: (heapsort' o deleteMin) h; in fun heapsort ls = (heapsort' o build) ls val test_0 = heapsort [] = [] val test_1 = heapsort [1,2,3] = [1, 2, 3] val test_2 = heapsort [1,3,2] = [1, 2, 3] val test_3 = heapsort [6,2,7,5,8,1,3,4] = [1, 2, 3, 4, 5, 6, 7, 8] end;
code/data_structures/src/tree/heap/priority_queue/README.md
# Priority Queue Description --- A priority queue is an abstract data type which is like a regular queue or stack data structure, but where additionally each element has a "priority" or a score associated with it. In a priority queue, an element with high priority is served before an element with low priority. If two elements have the same priority, they are served according to their order in the queue. This folder contains some Priority Queue implementations using a heap Priority Queue API --- - **pop()**: Removes the top element from the queue - **push()**: Inserts an item to the queue while maintaining the priority order - **top()**: Returns the top element of the queue (the item with the top priority) - **empty()**: Checks if the queue is empty Time Complexity --- pop() and push() take O(log n) and the others take O(1).
code/data_structures/src/tree/heap/priority_queue/leftist_tree/leftist_priority_queue.cpp
#include <iostream> #include <algorithm> struct Leftist { Leftist *left, *right; // dis is the distance to the right-bottom side of the tree int dis, value, size; Leftist(int val = 0) { left = NULL, right = NULL; dis = 0, value = val, size = 1; } ~Leftist() { delete left; delete right; } }; Leftist* merge(Leftist *x, Leftist *y) { // if x or y is NULL, return the other tree to be the answer if (x == NULL) return y; if (y == NULL) return x; if (y->value < x->value) std::swap(x, y); // We take x as new root, so add the size of y to x x->size += y->size; // merge the origin right sub-tree of x with y to construct the new right sub-tree of x x->right = merge(x->right, y); if (x->left == NULL && x->right != NULL) // if x->left is NULL pointer, swap the sub-trees to make it leftist std::swap(x->left, x->right); else if (x->right != NULL && x->left->dis < x->right->dis) // if the distance of left sub-tree is smaller, swap the sub-trees to make it leftist std::swap(x->left, x->right); // calculate the new distance if (x->right == NULL) x->dis = 0; else x->dis = x->right->dis + 1; return x; } Leftist* delete_root(Leftist *T) { //deleting root equals to make a new tree containing only left sub-tree and right sub-tree Leftist *my_left = T->left; Leftist *my_right = T->right; T->left = T->right = NULL; delete T; return merge(my_left, my_right); } int main() { Leftist *my_tree = new Leftist(10); // create a tree with root = 10 // adding a node to a tree is the same as creating a new tree and merge them together my_tree = merge(my_tree, new Leftist(100)); // push 100 my_tree = merge(my_tree, new Leftist(10000)); // push 10000 my_tree = merge(my_tree, new Leftist(1)); // push 1 my_tree = merge(my_tree, new Leftist(1266)); // push 1266 while (my_tree != NULL) { std::cout << my_tree->value << std::endl; my_tree = delete_root(my_tree); } return 0; } /* the output should be * 1 * 10 * 100 * 1266 * 10000 */
code/data_structures/src/tree/heap/priority_queue/priority_queue.js
/* Part of Cosmos by OpenGenus Foundation */ Array.prototype.swap = function(x, y) { let b = this[x]; this[x] = this[y]; this[y] = b; return this; }; /** * PriorityQueue constructor * @param data Initial data * @param compareFn compare function * @constructor */ function PriorityQueue(data, compareFn) { this.data = data || []; this.compareFn = compareFn || defaultCompareFn; this.push = push; this.pop = pop; this.top = top; this.init = init; this.empty = empty; this._up = up; this._down = down; this.init(); } /** * Initialises the priority queue */ function init() { if (this.data.length > 1) { let n = this.data.length; for (let i = Math.floor(n / 2 - 1); i >= 0; i -= 1) { this._down(i, n); } } } /** * Get the topmost item of the priority queue * @returns {*|Object} */ function top() { return this.data[0]; } /** * Is the queue empty? * @returns {boolean} */ function empty() { return this.data.length === 0; } /** * Pushes the item onto the heap */ function push(item) { this.data.push(item); this._up(this.data.length - 1); } /** * Pop removes the minimum element (according to Less) from the heap * and returns it. * * @returns {string|number|Object} */ function pop() { if (this.data.length === 0) { return undefined; } let n = this.data.length - 1; this.data.swap(0, n); this._down(0, n); return this.data.pop(); } /** * Default comparator function is for max heap * @param p First item to compare * @param q Second item to compare * * @returns {number} -1 if p < q, 1 if p > q or 0 if p == q */ function defaultCompareFn(p, q) { const diff = p - q; return diff < 0 ? -1 : diff > 0 ? 1 : 0; } /** * Percolate up from index * @param index */ function up(index) { while (index > 0) { let parentIndex = parent(index); let parentItem = this.data[parentIndex]; let currentItem = this.data[index]; if (parentIndex === index || !this.compareFn(currentItem, parentItem) < 0) { break; } this.data.swap(parentIndex, index); index = parentIndex; } } /** * Percolate down from index until n * @param index * @param n * * * @returns {boolean} True if a change happened. False otherwise. */ function down(index, n) { let i = index; while (true) { let currentItem = this.data[i]; let j1 = leftChild(i); if (j1 + 1 >= n || j1 < 0) { // overflows break; } let j = j1; // left child let j2 = j1 + 1; // right child if (j2 < n && this.compareFn(this.data[j2], this.data[j1]) < 0) { j = j2; } if (this.compareFn(this.data[j], currentItem) >= 0) { break; } this.data.swap(i, j); i = j; } return i > index; } /** * Return parent index * @param index current inter * @returns {number} parent index */ function parent(index) { return Math.floor((index - 1) / 2); } /** * Return left child index * @param index current inter * @returns {number} left child index */ function leftChild(index) { return index * 2 + 1; } function main() { const pq = new PriorityQueue([45, 6, 4, 3, 2, 72, 34, 12, 456, 29, 312]); pq.push(1); console.log(pq); } main();
code/data_structures/src/tree/heap/priority_queue/priority_queue.py
# Part of Cosmos by OpenGenus Foundation import math def default_compare_fn(p, q): diff = p - q if diff < 0: return -1 elif diff > 0: return 1 else: return 0 class PriorityQueue(object): def __init__(self, data=[], compare_fn=default_compare_fn): self.data = data self.compareFn = compare_fn self.init() def init(self): n = len(self.data) if n > 0: start = math.floor((n / 2) - 1) for i in range(int(start), 0, -1): self._down(i, n) def push(self, item): self.data.append(item) self._up(len(self.data) - 1) def pop(self): n = len(self.data) if n == 0: return None self.data[0], self.data[n - 1] = self.data[n - 1], self.data[0] self._down(0, n - 1) return self.data.pop() def _up(self, index): while index > 0: parent_index = int(math.floor((index - 1) / 2)) parent_item = self.data[parent_index] current_item = self.data[index] if ( parent_index == index or not self.compareFn(current_item, parent_item) < 0 ): break self.data[index], self.data[parent_index] = ( self.data[parent_index], self.data[index], ) index = parent_index def _down(self, index, n): i = index while True: current_item = self.data[i] j1 = 2 * i + 1 if j1 > n or j1 < 0: break j = j1 j2 = j1 + 1 if j2 < n and self.compareFn(self.data[j2], self.data[j1]) < 0: j = j2 if self.compareFn(self.data[j], current_item) >= 0: break self.data[j], self.data[i] = self.data[i], self.data[j] i = j return i > index def top(self): return self.data[0] def empty(self): return len(self.data) == 0 def __str__(self): return "PriorityQueue: {}".format(self.data) # return f'PriorityQueue: {self.data}' if __name__ == "__main__": pq = PriorityQueue([45, 6, 4, 3, 2, 72, 34, 12, 456, 29, 312]) pq.push(1) pq.pop() print(pq)
code/data_structures/src/tree/heap/soft_heap/soft_heap.cpp
/** * Soft Heap * Author: JonNRb * * Original paper: https://www.cs.princeton.edu/~chazelle/pubs/sheap.pdf * Binary heap version by Kaplan and Zwick */ #include <functional> #include <iterator> #include <limits> #include <list> #include <memory> #include <stdexcept> using namespace std; #if __cplusplus <= 201103L namespace { template <typename T, typename ... Args> unique_ptr<T> make_unique(Args&& ... args) { return unique_ptr<T>(new T(forward<Args>(args) ...)); } } // namespace #endif // `T` is a comparable type and higher values of `corruption` increase the // orderedness of the soft heap template <typename T> class SoftHeap { private: // `node`s make up elements in the soft queue, which is a binary heap with // "corrupted" entries struct node { typename list<T>::iterator super_key; unsigned rank; // `target_size` is a target for the number of corrupted nodes. the number // increases going up the heap and should be between 1 and 2 times the // `target_size` of its children -- unless it is `corruption` steps from the // bottom, in which case it is 1. unsigned target_size; // `link[0]` is the left node and `link[1]` is the right node unique_ptr<node> link[2]; // if `l` contains more than 1 entry, the node is "corrupted" list<T> l; }; struct head { // the root of a "soft queue": a binary heap of nodes unique_ptr<node> q; // iterator to the tree following this one with the minimum `super_key` at // the root. may be the current `head`. typename list<head>::iterator suffix_min; }; // doubly-linked list of all binary heaps (soft queues) in the soft heap list<head> l; unsigned corruption; public: SoftHeap(unsigned corruption) : corruption(corruption) { } bool empty() { return l.empty(); } void push(T item) { auto item_node = make_unique<node>(); item_node->rank = 0; item_node->target_size = 1; item_node->link[0] = nullptr; item_node->link[1] = nullptr; item_node->l.push_front(move(item)); item_node->super_key = item_node->l.begin(); l.emplace_front(); auto h = l.begin(); h->q = move(item_node); h->suffix_min = next(h) != l.end() ? next(h)->suffix_min : h; repeated_combine(1); } T pop() { if (l.empty()) throw invalid_argument("empty soft heap"); auto it = l.begin()->suffix_min; node* n = it->q.get(); T ret = move(*n->l.begin()); n->l.pop_front(); if (n->l.size() < n->target_size) { if (n->link[0] || n->link[1]) { sift(n); update_suffix_min(it); } else if (n->l.empty()) { if (it == l.begin()) l.erase(it); else { auto p = prev(it); l.erase(it); update_suffix_min(p); } } } return ret; } private: void update_suffix_min(typename list<head>::iterator it) const { if (it == l.end()) return; while (true) { if (next(it) == l.end()) it->suffix_min = it; else if (*it->q->super_key <= *next(it)->suffix_min->q->super_key) it->suffix_min = it; else it->suffix_min = next(it)->suffix_min; if (it == l.begin()) return; --it; } } unique_ptr<node> combine(unique_ptr<node> a, unique_ptr<node> b) const { auto n = make_unique<node>(); n->rank = a->rank + 1; n->target_size = n->rank <= corruption ? 1 : (3 * a->target_size + 1) / 2; n->link[0] = move(a); n->link[1] = move(b); sift(n.get()); return n; } void repeated_combine(unsigned max_rank) { auto it = l.begin(); for (auto next_it = next(l.begin()); next_it != l.end(); it = next_it, ++next_it) { if (it->q->rank == next_it->q->rank) { if (next(next_it) == l.end() || next(next_it)->q->rank != it->q->rank) { it->q = combine(move(it->q), move(next_it->q)); next_it = l.erase(next_it); if (next_it == l.end()) break; } } else if (it->q->rank > max_rank) break; } update_suffix_min(it); } static void sift(node* n) { while (n->l.size() < n->target_size) { if (n->link[1]) { if (!n->link[0] || *n->link[0]->super_key > *n->link[1]->super_key) swap(n->link[0], n->link[1]); } else if (!n->link[0]) return; n->super_key = n->link[0]->super_key; n->l.splice(n->l.end(), n->link[0]->l); if (!n->link[0]->link[0] && !n->link[0]->link[1]) n->link[0] = nullptr; else sift(n->link[0].get()); } } }; #include <chrono> #include <iostream> #include <random> #include <vector> int run_test_with_corruption(unsigned corruption, unsigned k_num_elems) { using namespace std::chrono; cout << "making soft heap with corruption " << corruption << " and " << k_num_elems << " elements..." << endl; SoftHeap<unsigned> sh(corruption); // create a random ordering of the numbers [0, k_num_elems) vector<bool> popped_nums(k_num_elems); vector<unsigned> nums(k_num_elems); random_device rd; mt19937 gen(rd()); for (unsigned i = 0; i < k_num_elems; ++i) nums[i] = i; for (unsigned i = 0; i < k_num_elems; ++i) { uniform_int_distribution<unsigned> dis(i, k_num_elems - 1); swap(nums[i], nums[dis(gen)]); } auto start = steady_clock::now(); for (unsigned i = 0; i < k_num_elems; ++i) sh.push(nums[i]); // this notion of `num_errs` is not rigorous in any way unsigned num_errs = 0; unsigned last = 0; while (!sh.empty()) { unsigned i = sh.pop(); if (popped_nums[i]) { cerr << " popped number " << i << " already" << endl; return -1; } popped_nums[i] = true; if (i < last) ++num_errs; last = i; // cout << i << endl; } auto end = steady_clock::now(); cout << " error rate: " << ((double)num_errs / k_num_elems) << endl; cout << " took " << duration_cast<milliseconds>(end - start).count() << " ms" << endl; return 0; } int main() { for (unsigned i = 0; i < 20; ++i) if (run_test_with_corruption(i, 1 << 18)) return -1; return 0; }
code/data_structures/src/tree/multiway_tree/fenwick_tree/README.md
# Fenwick Tree ## Explaination Fenwick Tree / Binary indexed tree is a data structure used to process interval/range based queries. Compared to segment tree data structure, Fenwick tree uses less space and is simpler to implement. One disadvantage of Fenwick tree is that it can be only used with an operation that is invertible. For example, addition is invertible so range sum queries can be processed, but max() is a non-invertible operation so range max queries can't be processed. ## Algorithm LeastSignificantBit operation is critical for working of Fenwick tree and is hidden within implementation details: ``` function LSB(i): return i & (-i) ``` A Fenwick tree preforms two functions: * query(b) -- Queries for the range `[1, b]`. query(b) - query(a - 1) queries for range `[a, b]`. ``` function query(b): while b &gt; 0: # process appropriately ... b = b - LSB(b) return ... ``` * update(pos, value) -- Updates index `pos` with `value`. ``` function update(pos, value): while pos &lt;= n: # Update array[pos] and FenwickTree[[pos] appropriately. ... pos = pos + LSB(pos) ``` ## Complexity __Space complexity__ : O(n) __Time complexity__ : * __Update__ : O(log<sub>2</sub>(n)) * __Query__ : O(log<sub>2</sub>(n)) Where n is the length of array. --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/data_structures/src/tree/multiway_tree/fenwick_tree/fenwick_tree.c
#include<stdio.h> // Part of Cosmos by OpenGenus Foundation int getSum(int bit_tree[], int index) { int sum = 0; // Iniialize result // index in bit_tree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of bit_tree[index] while (index>0) { // Add current element of bit_tree to sum sum += bit_tree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum; } void update(int bit_tree[], int n, int index, int val){ // index in bit_tree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while(index <=n){ // Add 'val' to current node of BI Tree bit_tree[index] += val; // Update index to that of parent in update View index += index & (-index); } return; } void constructBITtree(int arr[], int bit_tree[], int n){ //initialise bit_tree to 0 for(int i=1;i<=n;i++) bit_tree[i] = 0; //store value in bit_tree usin update for(int i=0;i<n;i++) update(bit_tree, n, i, arr[i]); return; } int main(){ int freq[] = {2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9}; int n =sizeof(freq)/sizeof(freq[0]); int bit_tree[n+1]; constructBITtree(freq, bit_tree, n); printf("Sum of elements in arr[0..5] is %d\n",getSum(bit_tree, 5)); // Let use test the update operation freq[3] += 6; update(bit_tree, n, 3, 6); //Update BIT for above change in arr[] printf("Sum of elements in arr[0..5] after the update is %d\n",getSum(bit_tree, 5)); return 0; }
code/data_structures/src/tree/multiway_tree/fenwick_tree/fenwick_tree.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> using namespace std; // Fenwick Tree (also known as Binary Indexed Tree or BIT) class BIT { public: int n; vector<int> arr; // constructor: initializes variables BIT(int n) { this->n = n; arr.resize(n + 1, 0); } // returns least significant bit int lsb(int idx) { return idx & -idx; } // updates the element at index idx by val void update(int idx, int val) // log(n) complexity { while (idx <= n) { arr[idx] += val; idx += lsb(idx); } } // returns prefix sum from 1 to idx int prefix(int idx) // log(n) complexity { int sum = 0; while (idx > 0) { sum += arr[idx]; idx -= lsb(idx); } return sum; } // returns sum of elements between indices l and r int range_query(int l, int r) // log(n) complexity { return prefix(r) - prefix(l - 1); } }; int main() { vector<int> array = {1, 2, 3, 4, 5}; int n = array.size(); BIT tree(n); for (int i = 0; i < n; i++) tree.update(i + 1, array[i]); cout << "Range Sum from 2 to 4: " << tree.range_query(2, 4) << endl; cout << "Range Sum from 1 to 5: " << tree.range_query(1, 5) << endl; }
code/data_structures/src/tree/multiway_tree/fenwick_tree/fenwick_tree.go
package main import "fmt" type FenwickTree struct { N int arr []int } func (bit *FenwickTree) Initialize(n int) { fmt.Println(n) bit.N = n bit.arr = make([]int, n+1) } func (bit *FenwickTree) lsb(idx int) int { return idx & -idx } func (bit *FenwickTree) Update(idx int, val int) { for ; idx <= bit.N; idx += bit.lsb(idx) { bit.arr[idx] += val } } func (bit *FenwickTree) PrefixSum(idx int) int { sum := 0 for ; idx > 0; idx -= bit.lsb(idx) { sum += bit.arr[idx] } return sum } func (bit *FenwickTree) RangeSum(l int, r int) int { return bit.PrefixSum(r) - bit.PrefixSum(l-1) } func main() { arr := []int{1, 2, 3, 4, 5} n := len(arr) var fenwick FenwickTree fenwick.Initialize(n) for i := 0; i < n; i++ { fenwick.Update(i+1, arr[i]) } fmt.Printf("Range sum from 2 to 4: %v\n", fenwick.RangeSum(2, 4)) fmt.Printf("Range sum from 1 to 5: %v\n", fenwick.RangeSum(1, 5)) }
code/data_structures/src/tree/multiway_tree/fenwick_tree/fenwick_tree.java
import java.util.*; import java.lang.*; import java.io.*; class BinaryIndexedTree { final static int MAX = 1000; // Max tree size static int BITree[] = new int[MAX]; /* n --> No. of elements present in input array. BITree[0..n] --> Array that represents Binary Indexed Tree. arr[0..n-1] --> Input array for whic prefix sum is evaluated. */ // Returns sum of arr[0..index]. This function assumes // that the array is preprocessed and partial sums of // array elements are stored in BITree[]. int getSum(int index) { int sum = 0; // Iniialize result // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse ancestors of BITree[index] while(index>0) { // Add current element of BITree to sum sum += BITree[index]; // Move index to parent node in getSum View index -= index & (-index); } return sum; } // Updates a node in Binary Index Tree (BITree) at given index // in BITree. The given value 'val' is added to BITree[i] and // all of its ancestors in tree. public static void updateBIT(int n, int index, int val) { // index in BITree[] is 1 more than the index in arr[] index = index + 1; // Traverse all ancestors and add 'val' while(index <= n) { // Add 'val' to current node of BIT Tree BITree[index] += val; // Update index to that of parent in update View index += index & (-index); } } /* Function to construct fenwick tree from given array.*/ void constructBITree(int arr[], int n) { // Initialize BITree[] as 0 for(int i=1; i<=n; i++) BITree[i] = 0; // Store the actual values in BITree[] using update() for(int i=0; i<n; i++) updateBIT(n, i, arr[i]); } // The Main function public static void main(String args[]) { int freq[] = {2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9}; int n = freq.length; BinaryIndexedTree tree = new BinaryIndexedTree(); // Build fenwick tree from given array tree.constructBITree(freq, n); System.out.println("Sum of elements in arr[0..5] is = " + tree.getSum(5)); // Let use test the update operation freq[3] += 6; updateBIT(n, 3, 6); //Update BIT for above change in arr[] // Find sum after the value is updated System.out.println("Sum of elements in arr[0..5] after update is = " + tree.getSum(5)); } }
code/data_structures/src/tree/multiway_tree/fenwick_tree/fenwick_tree.pl
#!/usr/bin/env perl use utf8; use 5.024; use warnings; use feature qw(signatures); no warnings qw(experimental::signatures); { package FenwickTree; sub new($class, %args) { return bless { arr => [ (0) x ($args{max}+1) ], # arr[k] = x[k-phi(k)+1] + ... + x[k] n => $args{max} + 1, }, 'FenwickTree'; } sub phi($n) { return $n & -$n; } sub get($self, $k) { # returns x[1] + x[2] + x[3] + ... + x[k] return $k <= 0 ? 0 : $self->{arr}->[$k] + $self->get( $k - phi($k) ); } sub add($self, $k, $c) { # x[k] += c return if $k > $self->{n}; $self->{arr}->[$k] += $c; $self->add( $k+phi($k), $c ); } } use Test::More tests => 2; my $tree = FenwickTree->new( max => 12 ); my @values = (2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9); $tree->add($_, $values[$_-1]) for (1..12); is( $tree->get(5), 2+1+1+3+2, 'sum of first 5 elements' ); $tree->add(4, 4); is( $tree->get(5), 2+1+1+(3+4)+2, 'sum after adding' );
code/data_structures/src/tree/multiway_tree/fenwick_tree/fenwick_tree.py
# Binary indexed tree or fenwick tree # Space Complexity: O(N) for declaring another array of N=size num_of_elements # Time Complexity: O(logN) for each operation(update and query as well) # original array for storing values for later lookup # Part of Cosmos by OpenGenus Foundation array = [] # array to store cumulative sum bit = [] """ index i in the bit[] array stores the cumulative sum from the index i to i - (1<<r) + 1 (both inclusive), where r represents the last set bit in the index i """ class FenwickTree: # To intialize list of num_of_elements+1 size def initialize(self, num_of_elements): for i in range(num_of_elements + 1): array.append(0) bit.append(0) def update(self, x, delta): while x <= num_of_elements: bit[x] = bit[x] + delta # x&(-x) gives the last set bit in a number x x = x + (x & -x) def query(self, x): range_sum = 0 while x > 0: range_sum = range_sum + bit[x] # x&(-x) gives the last set bit in a number x x = x - (x & -x) return range_sum fenwick_tree = FenwickTree() num_of_elements = int(input("Enter the size of list: ")) fenwick_tree.initialize(num_of_elements) for i in range(num_of_elements): # storing data in orginal list element = int(input("Enter the list element: ")) # updating the BIT array fenwick_tree.update(i + 1, element) number_of_queries = int(input("Enter number of queries: ")) for i in range(number_of_queries): left_index = int(input("Enter left index (1 indexing): ")) right_index = int(input("Enter right index (1 indexing): ")) if right_index < left_index: print("Invalid range ") continue print("Sum in range[%d,%d]: " % (left_index, right_index)) print(fenwick_tree.query(right_index) - fenwick_tree.query(left_index - 1))
code/data_structures/src/tree/multiway_tree/fenwick_tree/fenwick_tree_inversion_count.cpp
#include <iostream> #include <cstring> using namespace std; int BIT[101000], A[101000], n; int query(int i) { int ans = 0; for (; i > 0; i -= i & (-i)) ans += BIT[i]; return ans; } void update(int i) { for (; i <= n; i += i & (-i)) BIT[i]++; } int main() { int ans, i; while (cin >> n and n) { memset(BIT, 0, (n + 1) * (sizeof(int))); for (int i = 0; i < n; i++) cin >> A[i]; ans = 0; for (i = n - 1; i >= 0; i--) { ans += query(A[i] - 1); update(A[i]); } cout << ans << endl; } return 0; }
code/data_structures/src/tree/multiway_tree/red_black_tree/red_black_tree.c
/** * author: JonNRb <[email protected]> * license: GPLv3 * file: @cosmos//code/data_structures/red_black_tree/red_black.c * info: red black tree */ /** * guided by the wisdom of * http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_rbtree.aspx */ #include "red_black_tree.h" #include <errno.h> #include <stdlib.h> static inline int is_red(cosmos_red_black_node_t* node) { return node != NULL && node->red; } static int correct_rb_height(cosmos_red_black_tree_t tree) { if (tree == NULL) return 1; // NULL is a black node (black-height == 1) const int redness = is_red(tree); // red cannot neighbor red if (redness && (is_red(tree->link[0]) || is_red(tree->link[1]))) return -1; int black_height; // left and right subtrees must be correct and have same black height if ((black_height = correct_rb_height(tree->link[0])) < 0) return -1; if (black_height != correct_rb_height(tree->link[1])) return -1; return black_height + !redness; } /** * rrot = 1 (rrot = 0 is flipped) * * C B * / / \ * B => A C * / * A */ static void rotate(cosmos_red_black_tree_t* tree, int rrot) { cosmos_red_black_node_t* save = (*tree)->link[!rrot]; (*tree)->link[!rrot] = save->link[rrot]; save->link[rrot] = (*tree); (*tree)->red = 1; save->red = 0; *tree = save; } /** * rrot = 1 (rrot = 0 is flipped) * * E E C * / / / \ * A C A E * \ => / \ => \ / * C A D B D * / \ \ * B D B */ static void rotate_double(cosmos_red_black_tree_t* tree, int rrot) { if (tree == NULL) return; rotate(&(*tree)->link[!rrot], !rrot); rotate(tree, rrot); } /** * |tree| must be a black node with red children * * |path| encodes the index on the bottom layer for |tree| in the 2 level * subtree with root |grandparent| * * the case where |tree| has only one parent implies its parent is the root * which must be a black node (0, 1, 2, or 3) */ static inline void color_flip(cosmos_red_black_tree_t* tree, cosmos_red_black_tree_t* parent, cosmos_red_black_tree_t* grandparent, uint8_t path) { if (is_red((*tree)->link[0]) && is_red((*tree)->link[1])) { (*tree)->red = 1; (*tree)->link[0]->red = 0; (*tree)->link[1]->red = 0; } if (grandparent != NULL && is_red(*parent) && is_red(*tree)) { if (!(path % 3)) { rotate(grandparent, !(path % 2)); } else { rotate_double(grandparent, path % 2); } } } static void insert_impl(cosmos_red_black_tree_t* tree, cosmos_red_black_node_t* node) { cosmos_red_black_tree_t* it = tree; cosmos_red_black_tree_t* parent = NULL; cosmos_red_black_tree_t* grandparent = NULL; uint8_t path = 0; for (;;) { if (*it == NULL) { *it = node; path |= 4; } color_flip(it, parent, grandparent, path & 3); if (path & 4) break; int insert_right = *node->sort_key > *(*it)->sort_key; grandparent = parent; parent = it; it = &(*it)->link[insert_right]; path = (path % 2) * 2 + insert_right; } } static cosmos_red_black_node_t* pop_impl(cosmos_red_black_tree_t* tree, int from_right) { if (*tree == NULL) return NULL; if ((*tree)->link[from_right] == NULL) { cosmos_red_black_node_t* ret = *tree; *tree = (*tree)->link[!from_right]; return ret; } cosmos_red_black_tree_t* it = tree; cosmos_red_black_tree_t* parent = NULL; cosmos_red_black_node_t* sibling = NULL; for (;;) { // TODO(jonnrb): pop out special cases to make them easier to understand if (!is_red(*it) && !is_red((*it)->link[from_right])) { if (is_red((*it)->link[!from_right])) { rotate(it, from_right); } else if (sibling != NULL) { int recolor = 0; if (is_red(sibling->link[from_right])) { rotate_double(parent, from_right); recolor = 1; } else if (is_red(sibling->link[!from_right])) { rotate(parent, from_right); recolor = 1; } else { (*parent)->red = 0; sibling->red = 1; (*it)->red = 1; } if (recolor) { (*it)->red = 1; (*parent)->red = 1; (*parent)->link[0]->red = 0; (*parent)->link[1]->red = 0; } } } if ((*it)->link[from_right] == NULL) { cosmos_red_black_node_t* ret = *it; *it = (*it)->link[!from_right]; (*tree)->red = 0; ret->link[0] = NULL; ret->link[1] = NULL; return ret; } parent = it; it = &(*it)->link[from_right]; sibling = (*parent)->link[!from_right]; } } void cosmos_red_black_construct(cosmos_red_black_node_t* node) { node->red = 1; node->link[0] = NULL; node->link[1] = NULL; } int is_rb_correct(cosmos_red_black_tree_t tree) { return correct_rb_height(tree) >= 0; } void cosmos_red_black_push(cosmos_red_black_tree_t* tree, cosmos_red_black_node_t* node) { if (tree == NULL || node == NULL) { errno = EINVAL; return; } node->link[0] = NULL; node->link[1] = NULL; if (*tree == NULL) { *tree = node; return; } insert_impl(tree, node); (*tree)->red = 0; } cosmos_red_black_node_t* cosmos_red_black_pop_min( cosmos_red_black_tree_t* tree) { if (tree == NULL) { errno = EINVAL; return NULL; } return pop_impl(tree, 0); }
code/data_structures/src/tree/multiway_tree/red_black_tree/red_black_tree.cpp
#include <iostream> #include <memory> #include <cassert> #include <string> #include <stack> using namespace std; template<typename _Type, class _Derivative> class BaseNode { protected: using ValueType = _Type; using SPNodeType = std::shared_ptr<_Derivative>; public: BaseNode(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr) : value_(v), left_(l), right_(r) { } ValueType value() { return value_; } void value(ValueType v) { value_ = v; } SPNodeType &left() { return left_; } void left(SPNodeType l) { left_ = l; } SPNodeType &right() { return right_; } void right(SPNodeType r) { right_ = r; } protected: ValueType value_; SPNodeType left_, right_; }; template<typename _Type> class RBNode : public BaseNode<_Type, RBNode<_Type>> { private: using ValueType = _Type; using SPNodeType = std::shared_ptr<RBNode>; using WPNodeType = std::weak_ptr<RBNode>; public: enum class Color { RED, BLACK }; RBNode(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr, SPNodeType p = nullptr) : BaseNode<_Type, RBNode<_Type>>(v, l, r), parent_(p), color_(Color::RED) { } SPNodeType parent() { return parent_.lock(); } void parent(SPNodeType p) { parent_ = p; } Color color() { return color_; } void color(Color c) { color_ = c; } private: WPNodeType parent_; Color color_; }; struct RBTreeTest; template<typename _Type, typename _Compare = std::less<_Type>> class RBTree { private: typedef RBNode<_Type> NodeType; typedef std::shared_ptr<NodeType> SPNodeType; typedef typename RBNode<_Type>::Color Color; public: RBTree() : root_(nullptr), sentinel_(std::make_shared<NodeType>(0)), compare_(_Compare()) { sentinel_->left(sentinel_); sentinel_->right(sentinel_); sentinel_->parent(sentinel_); sentinel_->color(Color::BLACK); root_ = sentinel_; } void insert(_Type const &n); void erase(_Type const &n); SPNodeType const find(_Type const &); std::string preOrder() const; std::string inOrder() const; private: SPNodeType root_; SPNodeType sentinel_; _Compare compare_; SPNodeType &insert(SPNodeType &root, SPNodeType &pt); SPNodeType _find(_Type const &value); void rotateLeft(SPNodeType const &); void rotateRight(SPNodeType const &); void fixViolation(SPNodeType &); SPNodeType successor(SPNodeType const &); SPNodeType &sibling(SPNodeType const &); bool isLeftChild(SPNodeType const &); bool isRightChild(SPNodeType const &); void deleteOneNode(SPNodeType &); void deleteCase1(SPNodeType const &); void deleteCase2(SPNodeType const &); void deleteCase3(SPNodeType const &); void deleteCase4(SPNodeType const &); void deleteCase5(SPNodeType const &); void deleteCase6(SPNodeType const &); // for test friend RBTreeTest; }; template<typename _Type, typename _Compare> void RBTree<_Type, _Compare>::insert(_Type const &value) { SPNodeType pt = std::make_shared<NodeType>(value, sentinel_, sentinel_); root_ = insert(root_, pt); fixViolation(pt); } template<typename _Type, typename _Compare> void RBTree<_Type, _Compare>::erase(_Type const &value) { SPNodeType delete_node = _find(value); if (delete_node != sentinel_) { if (delete_node->left() == sentinel_) deleteOneNode(delete_node); else { SPNodeType smallest = successor(delete_node); auto temp = delete_node->value(); delete_node->value(smallest->value()); smallest->value(temp); deleteOneNode(smallest); } } } template<typename _Type, typename _Compare> void RBTree<_Type, _Compare>::deleteOneNode(SPNodeType &pt) { auto child = pt->left() != sentinel_ ? pt->left() : pt->right(); if (pt->parent() == sentinel_) { root_ = child; root_->parent(sentinel_); root_->color(Color::BLACK); } else { if (isLeftChild(pt)) pt->parent()->left(child); else pt->parent()->right(child); child->parent(pt->parent()); if (pt->color() == Color::BLACK) { if (child->color() == Color::RED) child->color(Color::BLACK); else deleteCase1(child); } } } template<typename _Type, typename _Compare> auto RBTree<_Type, _Compare>::find(_Type const &value)->SPNodeType const { auto pt = _find(value); return pt != sentinel_ ? pt : nullptr; } template<typename _Type, typename _Compare> std::string RBTree<_Type, _Compare>::preOrder() const { if (root_ == sentinel_) { return {}; } std::string elem{}; std::stack<SPNodeType> st{}; st.push(root_); elem.append(std::to_string(st.top()->value())); while (!st.empty()) { while (st.top()->left() != sentinel_) { elem.append(std::to_string(st.top()->left()->value())); st.push(st.top()->left()); } while (!st.empty() && st.top()->right() == sentinel_) st.pop(); if (!st.empty()) { elem.append(std::to_string(st.top()->right()->value())); auto temp = st.top(); st.pop(); st.push(temp->right()); } } return elem; } template<typename _Type, typename _Compare> std::string RBTree<_Type, _Compare>::inOrder() const { if (root_ == sentinel_) { return {}; } std::string elem{}; std::stack<SPNodeType> st{}; st.push(root_); while (!st.empty()) { while (st.top()->left() != sentinel_) st.push(st.top()->left()); while (!st.empty() && st.top()->right() == sentinel_) { elem.append(std::to_string(st.top()->value())); st.pop(); } if (!st.empty()) { elem.append(std::to_string(st.top()->value())); auto temp = st.top(); st.pop(); st.push(temp->right()); } } return elem; } template<typename _Type, typename _Compare> auto RBTree<_Type, _Compare>::insert(SPNodeType &root, SPNodeType &pt)->SPNodeType & { // If the tree is empty, return a new node if (root == sentinel_) { pt->parent(root->parent()); return pt; } // Otherwise, recur down the tree if (compare_(pt->value(), root->value())) { root->left(insert(root->left(), pt)); root->left()->parent(root); } else if (compare_(root->value(), pt->value())) { root->right(insert(root->right(), pt)); root->right()->parent(root); } else { pt->parent(root->parent()); pt->left(root->left()); pt->right(root->right()); pt->color(root->color()); } // return the (unchanged) node pointer return root; } template<typename _Type, typename _Compare> auto RBTree<_Type, _Compare>::_find(_Type const &value)->SPNodeType { auto pt = std::make_shared<NodeType>(value); std::stack<SPNodeType> st{}; st.push(root_); while (!st.empty()) { if (compare_(st.top()->value(), pt->value()) == compare_(pt->value(), st.top()->value())) return st.top(); while (st.top()->left() != sentinel_) { st.push(st.top()->left()); if (compare_(st.top()->value(), pt->value()) == compare_(pt->value(), st.top()->value())) return st.top(); } while (!st.empty() && st.top()->right() == sentinel_) st.pop(); if (!st.empty()) { if (compare_(st.top()->value(), pt->value()) == compare_(pt->value(), st.top()->value())) return st.top(); else { SPNodeType &temp = st.top(); st.pop(); st.push(temp->right()); } } } return sentinel_; } template<typename _Type, typename _Compare> void RBTree<_Type, _Compare>::rotateLeft(SPNodeType const &pt) { auto pt_right = pt->right(); pt->right() = pt_right->left(); if (pt->right() != sentinel_) pt->right()->parent(pt); pt_right->parent(pt->parent()); if (pt->parent() == sentinel_) root_ = pt_right; else if (pt == pt->parent()->left()) pt->parent()->left(pt_right); else pt->parent()->right(pt_right); pt_right->left(pt); pt->parent(pt_right); } template<typename _Type, typename _Compare> void RBTree<_Type, _Compare>::rotateRight(SPNodeType const &pt) { auto pt_left = pt->left(); pt->left(pt_left->right()); if (pt->left() != sentinel_) pt->left()->parent(pt); pt_left->parent(pt->parent()); if (pt->parent() == sentinel_) root_ = pt_left; else if (pt == pt->parent()->left()) pt->parent()->left(pt_left); else pt->parent()->right(pt_left); pt_left->right(pt); pt->parent(pt_left); } template<typename _Type, typename _Compare> auto RBTree<_Type, _Compare>::successor(SPNodeType const &pt)->SPNodeType { auto child = sentinel_; if (pt->left() != sentinel_) { child = pt->left(); while (child->right() != sentinel_) child = child->right(); } else if (pt->right() != sentinel_) { child = pt->right(); while (child->left() != sentinel_) child = child->left(); } return child; } template<typename _Type, typename _Compare> void RBTree<_Type, _Compare>::fixViolation(SPNodeType &pt) { auto parent_pt = sentinel_; auto grand_parent_pt = sentinel_; while (pt->color() == Color::RED && pt->parent()->color() == Color::RED) { parent_pt = pt->parent(); grand_parent_pt = pt->parent()->parent(); /* * Case : A * Parent of pt is left child of Grand-parent of pt */ if (parent_pt == grand_parent_pt->left()) { auto uncle_pt = grand_parent_pt->right(); /* * Case : 1 * The uncle of pt is also red * Only Recoloring required */ if (uncle_pt->color() == Color::RED) { grand_parent_pt->color(Color::RED); parent_pt->color(Color::BLACK); uncle_pt->color(Color::BLACK); pt = grand_parent_pt; } else { /* * Case : 2 * pt is right child of its parent * Left-rotation required */ if (pt == parent_pt->right()) { rotateLeft(parent_pt); pt = parent_pt; parent_pt = pt->parent(); } /* * Case : 3 * pt is left child of its parent * Right-rotation required */ rotateRight(grand_parent_pt); auto temp = parent_pt->color(); parent_pt->color(grand_parent_pt->color()); grand_parent_pt->color(temp); pt = parent_pt; } } /* * Case : B * Parent of pt is right child of Grand-parent of pt */ else { auto uncle_pt = grand_parent_pt->left(); /* * Case : 1 * The uncle of pt is also red * Only Recoloring required */ if (uncle_pt->color() == Color::RED) { grand_parent_pt->color(Color::RED); parent_pt->color(Color::BLACK); uncle_pt->color(Color::BLACK); pt = grand_parent_pt; } else { /* * Case : 2 * pt is left child of its parent * Right-rotation required */ if (pt == parent_pt->left()) { rotateRight(parent_pt); pt = parent_pt; parent_pt = pt->parent(); } /* * Case : 3 * pt is right child of its parent * Left-rotation required */ rotateLeft(grand_parent_pt); auto temp = parent_pt->color(); parent_pt->color(grand_parent_pt->color()); grand_parent_pt->color(temp); pt = parent_pt; } } } root_->color(Color::BLACK); } template<typename _Type, typename _Compare> auto RBTree<_Type, _Compare>::sibling(SPNodeType const &n)->SPNodeType & { return n->parent()->left() != n ? n->parent()->left() : n->parent()->right(); } template<typename _Type, typename _Compare> bool RBTree<_Type, _Compare>::isLeftChild(SPNodeType const &n) { return n == n->parent()->left(); } template<typename _Type, typename _Compare> bool RBTree<_Type, _Compare>::isRightChild(SPNodeType const &n) { return n == n->parent()->right(); } template<typename _Type, typename _Compare> void RBTree<_Type, _Compare>::deleteCase1(SPNodeType const &n) { if (n->parent() != sentinel_) deleteCase2(n); } template<typename _Type, typename _Compare> void RBTree<_Type, _Compare>::deleteCase2(SPNodeType const &n) { auto s = sibling(n); if (s->color() == Color::RED) { n->parent()->color(Color::RED); s->color(Color::BLACK); if (isLeftChild(n)) rotateLeft(n->parent()); else rotateRight(n->parent()); } deleteCase3(n); } template<typename _Type, typename _Compare> void RBTree<_Type, _Compare>::deleteCase3(SPNodeType const &n) { auto s = sibling(n); if (n->parent()->color() == Color::BLACK && s->color() == Color::BLACK && s->left()->color() == Color::BLACK && s->right()->color() == Color::BLACK) { s->color(Color::RED); deleteCase1(n->parent()); } else deleteCase4(n); } template<typename _Type, typename _Compare> void RBTree<_Type, _Compare>::deleteCase4(SPNodeType const &n) { auto s = sibling(n); if (n->parent()->color() == Color::RED && s->color() == Color::BLACK && s->left()->color() == Color::BLACK && s->right()->color() == Color::BLACK) { s->color(Color::RED); n->parent()->color(Color::BLACK); } else deleteCase5(n); } template<typename _Type, typename _Compare> void RBTree<_Type, _Compare>::deleteCase5(SPNodeType const &n) { auto s = sibling(n); if (s->color() == Color::BLACK) { if (isLeftChild(n) && s->right()->color() == Color::BLACK && s->left()->color() == Color::RED) { s->color(Color::RED); s->left()->color(Color::BLACK); rotateRight(s); } else if (isRightChild(n) && s->left()->color() == Color::BLACK && s->right()->color() == Color::RED) { s->color(Color::RED); s->right()->color(Color::BLACK); rotateLeft(s); } } deleteCase6(n); } template<typename _Type, typename _Compare> void RBTree<_Type, _Compare>::deleteCase6(SPNodeType const &n) { auto s = sibling(n); s->color(n->parent()->color()); n->parent()->color(Color::BLACK); if (isLeftChild(n)) { s->right()->color(Color::BLACK); rotateLeft(n->parent()); } else { s->left()->color(Color::BLACK); rotateRight(n->parent()); } }
code/data_structures/src/tree/multiway_tree/red_black_tree/red_black_tree.h
/** * author: JonNRb <[email protected]> * license: GPLv3 * file: @cosmos//code/data_structures/red_black_tree/red_black.h * info: red black tree */ #ifndef COSMOS_RED_BLACK_H_ #define COSMOS_RED_BLACK_H_ #include <stdint.h> /** * this macro subtracts off the offset of |member| within |type| from |ptr|, * allowing you to easily get a pointer to the containing struct of |ptr| * * ┌─────────────┬──────────┬──────┐ * |type| -> │ XXXXXXXXXXX │ |member| │ YYYY │ * └─────────────┴──────────┴──────┘ * ^ ^ * returns |ptr| */ #define container_of(ptr, type, member) \ ({ \ const typeof(((type*)0)->member)* __mptr = \ (const typeof(((type*)0)->member)*)(__mptr); \ (type*)((char*)ptr - __offsetof(type, member)); \ }) /** * node structure to be embedded in your data object. * * NOTE: it is expected that there will be a `uint64_t` immediately following * the embedded node (which will be used as a sorting key). */ typedef struct _cosmos_red_black_node cosmos_red_black_node_t; struct _cosmos_red_black_node { cosmos_red_black_node_t* link[2]; int red; uint64_t sort_key[0]; // place a `uint64_t` sort key immediately after this // struct in the data struct }; /** * represents a whole tree. should be initialized to NULL. */ typedef cosmos_red_black_node_t* cosmos_red_black_tree_t; /** * initializes a node to default values */ void cosmos_red_black_construct(cosmos_red_black_node_t* node); /** * takes a pointer to |tree| and |node| to insert. will update |tree| if * necessary. */ void cosmos_red_black_push(cosmos_red_black_tree_t* tree, cosmos_red_black_node_t* node); /** * takes a pointer to the |tree| and returns a pointer to the minimum node in * the tree, which is removed from |tree| */ cosmos_red_black_node_t* cosmos_red_black_pop_min( cosmos_red_black_tree_t* tree); #endif // COSMOS_RED_BLACK_H_
code/data_structures/src/tree/multiway_tree/red_black_tree/red_black_tree.java
public class RedBlackTree { // Part of Cosmos by OpenGenus Foundation public RedBlackTree( ) { header = new RedBlackNode( null ); header.left = header.right = nullNode; } private final int compare( Comparable item, RedBlackNode t ) { if( t == header ) return 1; else return item.compareTo( t.element ); } public void insert( Comparable item ) { current = parent = grand = header; nullNode.element = item; while( compare( item, current ) != 0 ) { great = grand; grand = parent; parent = current; current = compare( item, current ) < 0 ? current.left : current.right; if( current.left.color == RED && current.right.color == RED ) handleReorient( item ); } if( current != nullNode ) throw new DuplicateItemException( item.toString( ) ); current = new RedBlackNode( item, nullNode, nullNode ); if( compare( item, parent ) < 0 ) parent.left = current; else parent.right = current; handleReorient( item ); } public void remove( Comparable x ) { throw new UnsupportedOperationException( ); } public Comparable findMin( ) { if( isEmpty( ) ) return null; RedBlackNode itr = header.right; while( itr.left != nullNode ) itr = itr.left; return itr.element; } public Comparable findMax( ) { if( isEmpty( ) ) return null; RedBlackNode itr = header.right; while( itr.right != nullNode ) itr = itr.right; return itr.element; } public Comparable find( Comparable x ) { nullNode.element = x; current = header.right; for( ; ; ) { if( x.compareTo( current.element ) < 0 ) current = current.left; else if( x.compareTo( current.element ) > 0 ) current = current.right; else if( current != nullNode ) return current.element; else return null; } } public void makeEmpty( ) { header.right = nullNode; } public void printTree( ) { printTree( header.right ); } private void printTree( RedBlackNode t ) { if( t != nullNode ) { printTree( t.left ); System.out.println( t.element ); printTree( t.right ); } } public boolean isEmpty( ) { return header.right == nullNode; } private void handleReorient( Comparable item ) { current.color = RED; current.left.color = BLACK; current.right.color = BLACK; if( parent.color == RED ) { grand.color = RED; if( ( compare( item, grand ) < 0 ) != ( compare( item, parent ) < 0 ) ) parent = rotate( item, grand ); current = rotate( item, great ); current.color = BLACK; } header.right.color = BLACK; } private RedBlackNode rotate( Comparable item, RedBlackNode parent ) { if( compare( item, parent ) < 0 ) return parent.left = compare( item, parent.left ) < 0 ? rotateWithLeftChild( parent.left ) : rotateWithRightChild( parent.left ) ; else return parent.right = compare( item, parent.right ) < 0 ? rotateWithLeftChild( parent.right ) : rotateWithRightChild( parent.right ); } private static RedBlackNode rotateWithLeftChild( RedBlackNode k2 ) { RedBlackNode k1 = k2.left; k2.left = k1.right; k1.right = k2; return k1; } private static RedBlackNode rotateWithRightChild( RedBlackNode k1 ) { RedBlackNode k2 = k1.right; k1.right = k2.left; k2.left = k1; return k2; } private static class RedBlackNode { RedBlackNode( Comparable theElement ) { this( theElement, null, null ); } RedBlackNode( Comparable theElement, RedBlackNode lt, RedBlackNode rt ) { element = theElement; left = lt; right = rt; color = RedBlackTree.BLACK; } Comparable element; RedBlackNode left; RedBlackNode right; int color; } private RedBlackNode header; private static RedBlackNode nullNode; static { nullNode = new RedBlackNode( null ); nullNode.left = nullNode.right = nullNode; } private static final int BLACK = 1; private static final int RED = 0; private static RedBlackNode current; private static RedBlackNode parent; private static RedBlackNode grand; private static RedBlackNode great; // MAIN TO TEST FOR ERRORS public static void main( String [ ] args ) { RedBlackTree t = new RedBlackTree( ); final int NUMS = 400000; final int GAP = 35461; System.out.println( "Checking... (no more output means success)" ); for( int i = GAP; i != 0; i = ( i + GAP ) % NUMS ) t.insert( new Integer( i ) ); if( ((Integer)(t.findMin( ))).intValue( ) != 1 || ((Integer)(t.findMax( ))).intValue( ) != NUMS - 1 ) System.out.println( "FindMin or FindMax error!" ); for( int i = 1; i < NUMS; i++ ) if( ((Integer)(t.find( new Integer( i ) ))).intValue( ) != i ) System.out.println( "Find error1!" ); } private class DuplicateItemException extends RuntimeException { public DuplicateItemException( ) { super( ); } public DuplicateItemException( String message ) { super( message ); } } }
code/data_structures/src/tree/multiway_tree/red_black_tree/red_black_tree.rb
class Node attr_accessor :data, :color, :left, :right, :parent def initialize(data) @data = data @color = 'red' @left = nil @right = nil @parent = nil end def isSingle @left.nil? && @right.nil? end def addChildLeft(node) @left = node node.parent = self end def addChildRight(node) @right = node node.parent = self end def grandparent return nil if @parent.nil? @parent.parent end def sibling if @parent.nil? nil elsif @parent.left == self @parent.right else @parent.left end end def uncle if @parent.nil? || @parent.parent.nil? nil else @parent.sibling end end def rotateLeft tmp = right self.right = tmp.left tmp.left = self tmp.parent = parent if parent.left == self parent.left = tmp else parent.right = tmp end self.parent = tmp end def rotateRight tmp = left self.left = tmp.right tmp.right = self tmp.parent = parent if parent.left == self parent.left = tmp else parent.right = tmp end self.parent = tmp end end class RedBlackTree attr_accessor :head def initialize @head = nil end def insert(value) tmp = Node.new(value) if @head.nil? @head = tmp else current = @head until current.nil? if value < current.data if !current.left.nil? current = current.left else current.left = tmp break end elsif value > current.data if !current.right.nil? current = current.right else current.right = tmp break end else puts "Value #{value} already in tree" return end end end insert_repair(tmp) end def insert_repair(node) uncle = node.uncle() grandparent = node.grandparent() if node.parent.nil? node.color = 'black' elsif node.parent.color == 'black' return elsif !uncle.nil? && (uncle.color == 'red') node.parent.parent.color = 'red' node.parent.color = 'black' uncle.color = 'black' insert_repair(node.parent.parent) elsif uncle.nil? || (uncle.color == 'black') if node == grandparent.left.right rotateLeft(node.parent) node = node.left elsif node == grandparent.right.left rotateRight(node.parent) node = node.right end if node.parent.left == node rotateRight(grandparent) else rotateLeft(grandparent) end node.parent.color = 'black' node.grandparent.color = 'red' end end def search(value) current = head until current.nil? if value < current.data current = current.left elsif value > current.data current = current.right else puts "Element #{value} Found" return end end puts "Element #{value} not Found" end end
code/data_structures/src/tree/multiway_tree/red_black_tree/red_black_tree.scala
// From http://scottlobdell.me/2016/02/purely-functional-red-black-trees-python/ case class RBTree[T](left: RBTree[T], value: T, right: RBTree[T], isBlack: Boolean) { val height: Int = { val leftHeight = if (left == null) 0 else left.height val rightHeight = if (right == null) 0 else right.height Math.max(leftHeight, rightHeight) } def insert(value: T)(implicit ord: Ordering[T]): RBTree[T] = update(RBTree(null, value, null, false)).blacken() def balance(): RBTree[T] = { if (!isBlack) { this } else if (left != null && !left.isBlack) { if (right != null && !right.isBlack) recolored() else if (left.left != null && !left.left.isBlack) rotateRight().recolored() else if (left.right != null && !left.right.isBlack) this.copy(left = left.rotateLeft()).rotateRight().recolored() else this } else if (right != null && !right.isBlack) { if (right.right != null && !right.right.isBlack) rotateLeft().recolored() else if (right.left != null && !right.left.isBlack) this.copy(right = right.rotateRight()).rotateLeft().recolored() else this } else this } def update(node: RBTree[T])(implicit ord: Ordering[T]): RBTree[T] = { if (ord.lt(node.value, value)) { if (left == null) this.copy(left = node.balance()).balance() else this.copy(left = left.update(node).balance()).balance() } else { if (right == null) this.copy(right = node.balance()).balance() else this.copy(right = right.update(node).balance()).balance() } } def blacken(): RBTree[T] = { if (isBlack) this else this.copy(isBlack = true) } def recolored() = RBTree(left.blacken(), value, right.blacken(), false) def rotateLeft(): RBTree[T] = right.copy(left = this.copy(right = right.left)) def rotateRight(): RBTree[T] = left.copy(right = this.copy(left = left.right)) def isMember(other: T)(implicit ord: Ordering[T]): Boolean = { if (ord.lt(other, value)) left.isMember(other) else if (ord.gt(other, value)) right.isMember(other) else true } } object Main { def main(args: Array[String]): Unit = { println(RBTree(null, 7, null, false).insert(6).insert(3)) println(RBTree(null, 1, null, false).insert(2)) println(RBTree(null, 1, null, false).insert(2).insert(3)) println(RBTree(null, 1, null, false).insert(2).insert(3).insert(4).insert(5)) println(RBTree(null, 1, null, false).insert(2).insert(3).insert(4).insert(5).insert(6)) println(RBTree(null, 1, null, false).insert(2).insert(3).insert(4).insert(5).insert(6).insert(7)) } }
code/data_structures/src/tree/multiway_tree/red_black_tree/red_black_tree.test.cpp
#include "red_black_tree.cpp" void test() { std::shared_ptr<RBTree<int>> rbt; rbt = make_shared<RBTree<int>>(); rbt->find(3); assert(rbt->preOrder() == ""); assert(rbt->find(32) == nullptr); rbt->insert(1); rbt->insert(4); rbt->insert(7); rbt->insert(10); rbt->insert(2); rbt->insert(6); rbt->insert(8); rbt->insert(3); rbt->insert(5); rbt->insert(9); rbt->insert(100); assert(rbt->preOrder() == "74213659810100"); rbt->insert(40); assert(rbt->preOrder() == "7421365984010100"); rbt->insert(30); assert(rbt->preOrder() == "742136598401030100"); rbt->insert(20); assert(rbt->preOrder() == "74213659840201030100"); rbt->insert(15); assert(rbt->preOrder() == "7421365209810154030100"); rbt->insert(50); assert(rbt->preOrder() == "742136520981015403010050"); rbt->insert(60); assert(rbt->preOrder() == "74213652098101540306050100"); rbt->insert(70); assert(rbt->preOrder() == "7421365209810154030605010070"); rbt->insert(80); assert(rbt->preOrder() == "742136520981015403060508070100"); rbt->insert(63); assert(rbt->preOrder() == "74213652098101560403050807063100"); rbt->insert(67); assert(rbt->preOrder() == "7421365209810156040305080676370100"); rbt->insert(65); rbt->insert(69); rbt->insert(37); rbt->insert(33); rbt->insert(35); rbt->insert(31); assert(rbt->inOrder() == "1234567891015203031333537405060636567697080100"); assert(rbt->preOrder() == "2074213659810156040333031373550806763657069100"); assert(rbt->find(31) != nullptr); assert(rbt->find(32) == nullptr); rbt->erase(69); assert(rbt->preOrder() == "20742136598101560403330313735508067636570100"); rbt->erase(65); assert(rbt->preOrder() == "207421365981015604033303137355080676370100"); rbt->erase(1); assert(rbt->preOrder() == "20742365981015604033303137355080676370100"); rbt->erase(3); assert(rbt->preOrder() == "2074265981015604033303137355080676370100"); rbt->erase(2); assert(rbt->preOrder() == "207546981015604033303137355080676370100"); rbt->erase(60); assert(rbt->preOrder() == "2075469810155033303137354080676370100"); rbt->erase(35); assert(rbt->preOrder() == "20754698101550333031374080676370100"); rbt->erase(37); assert(rbt->preOrder() == "207546981015503330314080676370100"); rbt->erase(40); assert(rbt->preOrder() == "2075469810155031303380676370100"); rbt->erase(50); assert(rbt->preOrder() == "20754698101567333130638070100"); rbt->erase(20); assert(rbt->preOrder() == "157546981067333130638070100"); rbt->erase(15); assert(rbt->preOrder() == "1075469867333130638070100"); rbt->erase(10); assert(rbt->preOrder() == "97546867333130638070100"); rbt->erase(9); assert(rbt->preOrder() == "8547667333130638070100"); rbt->erase(100); assert(rbt->preOrder() == "8547667333130638070"); rbt->erase(70); assert(rbt->preOrder() == "85476673331306380"); rbt->erase(80); assert(rbt->preOrder() == "854763331306763"); } // test of RBTree methods struct RBTreeTest { typedef RBTree<int> tree_type; using node_type = tree_type::NodeType; using p_node_type = tree_type::SPNodeType; using Color = tree_type::Color; RBTreeTest() { testSibling(); // below test of delete cases need ignore invoke testDeleteCase2(); testDeleteCase3(); testDeleteCase4(); testDeleteCase5(); testDeleteCase6(); } void testSibling() { tree_type t; p_node_type n = std::make_shared<node_type>(0), l = std::make_shared<node_type>(0), r = std::make_shared<node_type>(0); n->left(l); n->right(r); l->parent(n); r->parent(n); assert(t.sibling(l) == r); assert(t.sibling(r) == l); } void testDeleteCase2() { tree_type t; p_node_type n = std::make_shared<node_type>(0), p = std::make_shared<node_type>(0), s = std::make_shared<node_type>(0), sl = std::make_shared<node_type>(0), sr = std::make_shared<node_type>(0); // test n is left of parent p->color(Color::BLACK); s->color(Color::RED); sr->right(t.sentinel_); sr->left(sr->right()); sl->right(sr->left()); sl->left(sl->right()); n->right(sl->left()); n->left(n->right()); p->parent(n->left()); p->left(n); p->right(s); s->parent(p); n->parent(s->parent()); s->left(sl); s->right(sr); sr->parent(s); sl->parent(sr->parent()); t.deleteCase2(n); assert(p->color() == Color::RED); assert(s->color() == Color::BLACK); assert(s->parent() == t.sentinel_); assert(n->left() == t.sentinel_); assert(n->right() == t.sentinel_); assert(sl->left() == t.sentinel_); assert(sl->right() == t.sentinel_); assert(sr->left() == t.sentinel_); assert(sr->right() == t.sentinel_); assert(s->left() == p); assert(s->right() == sr); assert(p->parent() == s); assert(sr->parent() == s); assert(p->left() == n); assert(p->right() == sl); assert(n->parent() == p); assert(sl->parent() == p); // test n is right of parent p->color(Color::BLACK); s->color(Color::RED); sr->right(t.sentinel_); sr->left(sr->right()); sl->right(sr->left()); sl->left(sl->right()); n->right(sl->left()); n->left(n->right()); p->parent(n->left()); p->left(s); p->right(n); s->parent(p); n->parent(s->parent()); s->left(sl); s->right(sr); sr->parent(s); sl->parent(sr->parent()); t.deleteCase2(n); assert(p->color() == Color::RED); assert(s->color() == Color::BLACK); assert(s->parent() == t.sentinel_); assert(n->left() == t.sentinel_); assert(n->right() == t.sentinel_); assert(sl->left() == t.sentinel_); assert(sl->right() == t.sentinel_); assert(sr->left() == t.sentinel_); assert(sr->right() == t.sentinel_); assert(s->left() == sl); assert(s->right() == p); assert(sl->parent() == s); assert(p->parent() == s); assert(p->left() == sr); assert(p->right() == n); assert(sr->parent() == p); assert(n->parent() == p); } void testDeleteCase3() { tree_type t; p_node_type n = std::make_shared<node_type>(0), p = std::make_shared<node_type>(0), s = std::make_shared<node_type>(0), sl = std::make_shared<node_type>(0), sr = std::make_shared<node_type>(0); sr->color(Color::BLACK); sl->color(sr->color()); s->color(sl->color()); p->color(s->color()); n->color(p->color()); sr->right(t.sentinel_); sr->left(sr->right()); sl->right(sr->left()); sl->left(sl->right()); n->right(sl->left()); n->left(n->right()); p->parent(n->left()); p->left(n); p->right(s); s->parent(p); n->parent(s->parent()); s->left(sl); s->right(sr); sr->parent(s); sl->parent(sr->parent()); t.deleteCase3(n); assert(s->color() == Color::RED); assert(p->color() == Color::BLACK); assert(n->color() == Color::BLACK); assert(sl->color() == Color::BLACK); assert(sr->color() == Color::BLACK); sr->color(Color::BLACK); sl->color(sr->color()); s->color(sl->color()); p->color(s->color()); n->color(p->color()); sr->right(t.sentinel_); sr->left(sr->right()); sl->right(sr->left()); sl->left(sl->right()); n->right(sl->left()); n->left(n->right()); p->parent(n->left()); p->left(s); p->right(n); s->parent(p); n->parent(s->parent()); s->left(sl); s->right(sr); sr->parent(s); sl->parent(sr->parent()); t.deleteCase3(n); assert(s->color() == Color::RED); assert(p->color() == Color::BLACK); assert(n->color() == Color::BLACK); assert(sl->color() == Color::BLACK); assert(sr->color() == Color::BLACK); } void testDeleteCase4() { tree_type t; p_node_type n = std::make_shared<node_type>(0), p = std::make_shared<node_type>(0), s = std::make_shared<node_type>(0), sl = std::make_shared<node_type>(0), sr = std::make_shared<node_type>(0); sr->color(Color::BLACK); sl->color(sr->color()); s->color(sl->color()); n->color(s->color()); p->color(Color::RED); sr->right(t.sentinel_); sr->left(sr->right()); sl->right(sr->left()); sl->left(sl->right()); n->right(sl->left()); n->left(n->right()); p->parent(n->left()); p->left(n); p->right(s); s->parent(p); n->parent(s->parent()); s->left(sl); s->right(sr); sr->parent(s); sl->parent(sr->parent()); t.deleteCase4(n); assert(s->color() == Color::RED); assert(p->color() == Color::BLACK); assert(n->color() == Color::BLACK); assert(sl->color() == Color::BLACK); assert(sr->color() == Color::BLACK); sr->color(Color::BLACK); sl->color(sr->color()); s->color(sl->color()); n->color(s->color()); p->color(Color::RED); sr->right(t.sentinel_); sr->left(sr->right()); sl->right(sr->left()); sl->left(sl->right()); n->right(sl->left()); n->left(n->right()); p->parent(n->left()); p->left(s); p->right(n); s->parent(p); n->parent(s->parent()); s->left(sl); s->right(sr); sr->parent(s); sl->parent(sr->parent()); t.deleteCase4(n); assert(s->color() == Color::RED); assert(p->color() == Color::BLACK); assert(n->color() == Color::BLACK); assert(sl->color() == Color::BLACK); assert(sr->color() == Color::BLACK); } void testDeleteCase5() { tree_type t; p_node_type n = std::make_shared<node_type>(0), p = std::make_shared<node_type>(0), s = std::make_shared<node_type>(0), sl = std::make_shared<node_type>(0), sr = std::make_shared<node_type>(0), s_l = std::make_shared<node_type>(0), s_r = std::make_shared<node_type>(0); s_r->color(Color::BLACK); s_l->color(s_r->color()); sr->color(s_l->color()); s->color(sr->color()); p->color(s->color()); n->color(p->color()); sl->color(Color::RED); s_r->right(t.sentinel_); s_r->left(s_r->right()); s_l->right(s_r->left()); s_l->left(s_l->right()); sr->right(s_l->left()); sr->left(sr->right()); n->right(sr->left()); n->left(n->right()); p->parent(n->left()); p->left(n); p->right(s); s->parent(p); n->parent(s->parent()); s->left(sl); s->right(sr); sr->parent(s); sl->parent(sr->parent()); sl->left(s_l); sl->right(s_r); s_r->parent(sl); s_l->parent(s_r->parent()); t.deleteCase5(n); assert(s->color() == Color::RED); assert(p->color() == Color::BLACK); assert(n->color() == Color::BLACK); assert(sl->color() == Color::BLACK); assert(sr->color() == Color::BLACK); assert(s_l->color() == Color::BLACK); assert(s_r->color() == Color::BLACK); assert(p->parent() == t.sentinel_); assert(n->left() == t.sentinel_); assert(n->right() == t.sentinel_); assert(sr->left() == t.sentinel_); assert(sr->right() == t.sentinel_); assert(s_l->left() == t.sentinel_); assert(s_l->right() == t.sentinel_); assert(s_r->left() == t.sentinel_); assert(s_r->right() == t.sentinel_); assert(p->left() == n); assert(p->right() == sl); assert(n->parent() == p); assert(sl->parent() == p); assert(sl->left() == s_l); assert(sl->right() == s); assert(s_l->parent() == sl); assert(s->parent() == sl); assert(s->left() == s_r); assert(s->right() == sr); assert(s_r->parent() == s); assert(sr->parent() == s); s_r->color(Color::BLACK); s_l->color(s_r->color()); sl->color(s_l->color()); s->color(sl->color()); p->color(s->color()); n->color(p->color()); sr->color(Color::RED); s_r->right(t.sentinel_); s_r->left(s_r->right()); s_l->right(s_r->left()); s_l->left(s_l->right()); sl->right(s_l->left()); sl->left(sl->right()); n->right(sl->left()); n->left(n->right()); p->parent(n->left()); p->left(s); p->right(n); s->parent(p); n->parent(s->parent()); s->left(sl); s->right(sr); sr->parent(s); sl->parent(sr->parent()); sr->left(s_l); sr->right(s_r); s_r->parent(sr); s_l->parent(s_r->parent()); t.deleteCase5(n); assert(s->color() == Color::RED); assert(p->color() == Color::BLACK); assert(n->color() == Color::BLACK); assert(sl->color() == Color::BLACK); assert(sr->color() == Color::BLACK); assert(s_l->color() == Color::BLACK); assert(s_r->color() == Color::BLACK); assert(p->parent() == t.sentinel_); assert(n->left() == t.sentinel_); assert(n->right() == t.sentinel_); assert(sl->left() == t.sentinel_); assert(sl->right() == t.sentinel_); assert(s_l->left() == t.sentinel_); assert(s_l->right() == t.sentinel_); assert(s_r->left() == t.sentinel_); assert(s_r->right() == t.sentinel_); assert(p->left() == sr); assert(p->right() == n); assert(n->parent() == p); assert(sr->parent() == p); assert(sr->left() == s); assert(sr->right() == s_r); assert(s->parent() == sr); assert(s_r->parent() == sr); assert(s->left() == sl); assert(s->right() == s_l); assert(sl->parent() == s); assert(s_l->parent() == s); } void testDeleteCase6() { tree_type t; p_node_type n = std::make_shared<node_type>(0), p = std::make_shared<node_type>(0), s = std::make_shared<node_type>(0), sc = std::make_shared<node_type>(0); s->color(Color::BLACK); n->color(s->color()); p->color(n->color()); sc->color(Color::RED); sc->right(t.sentinel_); sc->left(sc->right()); s->left(sc->left()); n->right(s->left()); n->left(n->right()); p->parent(n->left()); p->left(n); p->right(s); n->parent(p); s->parent(p); s->right(sc); sc->parent(s); t.deleteCase6(n); assert(p->color() == Color::BLACK); assert(n->color() == Color::BLACK); assert(s->color() == Color::BLACK); assert(sc->color() == Color::BLACK); assert(s->parent() == t.sentinel_); assert(n->left() == t.sentinel_); assert(n->right() == t.sentinel_); assert(p->right() == t.sentinel_); assert(sc->left() == t.sentinel_); assert(sc->right() == t.sentinel_); assert(s->left() == p); assert(s->right() == sc); assert(p->parent() == s); assert(sc->parent() == s); assert(p->left() == n); assert(n->parent() == p); s->color(Color::BLACK); n->color(s->color()); p->color(n->color()); sc->color(Color::RED); sc->right(t.sentinel_); sc->left(sc->right()); s->right(sc->left()); n->right(s->right()); n->left(n->right()); p->parent(n->left()); p->left(s); p->right(n); s->parent(p); n->parent(p); s->left(sc); sc->parent(s); t.deleteCase6(n); assert(p->color() == Color::BLACK); assert(n->color() == Color::BLACK); assert(s->color() == Color::BLACK); assert(sc->color() == Color::BLACK); assert(s->parent() == t.sentinel_); assert(n->left() == t.sentinel_); assert(n->right() == t.sentinel_); assert(p->left() == t.sentinel_); assert(sc->left() == t.sentinel_); assert(sc->right() == t.sentinel_); assert(s->left() == sc); assert(s->right() == p); assert(sc->parent() == s); assert(p->parent() == s); assert(p->right() == n); assert(n->parent() == p); } }; // Driver Code int main() { RBTreeTest t; test(); return 0; }
code/data_structures/src/tree/multiway_tree/splay_tree/readme.md
# Splay Tree > Your personal library of every algorithm and data structure code that you will ever encounter A splay tree is a self-adjusting Binary Search Tree with the additional property that recently accessed elements are quick to access again ( O(1) time). It performs basic operations such as insertion, look-up and removal in O(log n) amortized time. For many sequences of non-random operations, splay trees perform better than other search trees, even when the specific pattern of the sequence is unknown. All normal operations on a binary search tree are combined with one basic operation, called splaying. Splaying the tree for a certain element rearranges the tree so that the element is placed at the root of the tree. --- <p align="center"> A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a> </p> ---
code/data_structures/src/tree/multiway_tree/splay_tree/splay_tree.cpp
/* * Part of Cosmos by OpenGenus Foundation * * splay tree synopsis * * template<typename _Type, class _Derivative> * class Node * { * protected: * using SPNodeType = std::shared_ptr<_Derivative>; * using ValueType = _Type; * * public: * Node(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr); * * ValueType value(); * * void value(ValueType v); * * SPNodeType left(); * * void left(SPNodeType l); * * SPNodeType right(); * * void right(SPNodeType r); * * protected: * ValueType value_; * std::shared_ptr<_Derivative> left_, right_; * }; * * template<typename _Type> * class DerivativeNode :public Node<_Type, DerivativeNode<_Type>> * { * private: * using BaseNode = Node<_Type, DerivativeNode<_Type>>; * using SPNodeType = typename BaseNode::SPNodeType; * using WPNodeType = std::weak_ptr<DerivativeNode>; * using ValueType = typename BaseNode::ValueType; * * public: * DerivativeNode(ValueType v, * SPNodeType l = nullptr, * SPNodeType r = nullptr, * WPNodeType p = WPNodeType()); * * SPNodeType parent(); * * void parent(SPNodeType p); * * private: * WPNodeType parent_; * }; * * template<typename _Type, * typename _Compare = std::less<_Type>, * class NodeType = DerivativeNode<_Type>> * class SplayTree * { * private: * using SPNodeType = std::shared_ptr<NodeType>; * * public: * using ValueType = _Type; * using Reference = ValueType &; * using ConstReference = ValueType const &; * using SizeType = size_t; * using DifferenceType = std::ptrdiff_t; * * SplayTree() :root_(nullptr), size_(0), compare_(_Compare()) * * SizeType insert(ConstReference value); * * SizeType erase(ConstReference value); * * SPNodeType find(ConstReference value); * * SPNodeType minimum() const; * * SPNodeType maximum() const; * * SizeType height() const; * * SizeType size() const; * * bool empty() const; * * void inorderTravel(std::ostream &output) const; * * void preorderTravel(std::ostream &output) const; * * private: * SPNodeType root_; * SizeType size_; * _Compare compare_; * * SPNodeType splay(SPNodeType n); * * void leftRotate(SPNodeType n); * * void rightRotate(SPNodeType n); * * void replace(SPNodeType old, SPNodeType new_); * * SPNodeType get(ConstReference value); * * SizeType height(SPNodeType n) const; * * SPNodeType minimum(SPNodeType n) const; * * SPNodeType maximum(SPNodeType n) const; * * void inorderTravel(std::ostream &output, SPNodeType n) const; * * void preorderTravel(std::ostream &output, SPNodeType n) const; * }; */ #include <functional> #include <algorithm> #include <memory> #include <cstddef> template<typename _Type, class _Derivative> class Node { protected: using SPNodeType = std::shared_ptr<_Derivative>; using ValueType = _Type; public: Node(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr) : value_(v), left_(l), right_(r) { }; ValueType value() { return value_; } void value(ValueType v) { value_ = v; } SPNodeType left() { return left_; } void left(SPNodeType l) { left_ = l; } SPNodeType right() { return right_; } void right(SPNodeType r) { right_ = r; } protected: ValueType value_; std::shared_ptr<_Derivative> left_, right_; }; template<typename _Type> class DerivativeNode : public Node<_Type, DerivativeNode<_Type>> { private: using BaseNode = Node<_Type, DerivativeNode<_Type>>; using SPNodeType = typename BaseNode::SPNodeType; using WPNodeType = std::weak_ptr<DerivativeNode>; using ValueType = typename BaseNode::ValueType; public: DerivativeNode(ValueType v, SPNodeType l = nullptr, SPNodeType r = nullptr, WPNodeType p = WPNodeType()) : BaseNode(v, l, r), parent_(p) { }; SPNodeType parent() { return parent_.lock(); } void parent(SPNodeType p) { parent_ = p; } private: WPNodeType parent_; }; template<typename _Type, typename _Compare = std::less<_Type>, class NodeType = DerivativeNode<_Type>> class SplayTree { private: using SPNodeType = std::shared_ptr<NodeType>; public: using ValueType = _Type; using Reference = ValueType &; using ConstReference = ValueType const &; using SizeType = size_t; using DifferenceType = std::ptrdiff_t; SplayTree() : root_(nullptr), size_(0), compare_(_Compare()) { ; } SizeType insert(ConstReference value) { SPNodeType n = root_, parent = nullptr; while (n) { parent = n; if (compare_(n->value(), value)) n = n->right(); else if (compare_(value, n->value())) n = n->left(); else { n->value(value); return 0; } } n = std::make_shared<NodeType>(value); n->parent(parent); if (parent == nullptr) root_ = n; else if (compare_(parent->value(), n->value())) parent->right(n); else parent->left(n); splay(n); ++size_; return 1; } SizeType erase(ConstReference value) { SPNodeType n = get(value); if (n) { splay(n); if (n->left() == nullptr) replace(n, n->right()); else if (n->right() == nullptr) replace(n, n->left()); else { SPNodeType min = minimum(n->right()); if (min->parent() != n) { replace(min, min->right()); min->right(n->right()); min->right()->parent(min); } replace(n, min); min->left(n->left()); min->left()->parent(min); } --size_; return 1; } return 0; } SPNodeType find(ConstReference value) { return get(value); } SPNodeType minimum() const { return minimum(root_); } SPNodeType maximum() const { return maximum(root_); } SizeType height() const { return height(root_); } SizeType size() const { return size_; } bool empty() const { return size_ == 0; } void inorderTravel(std::ostream &output) const { inorderTravel(output, root_); } void preorderTravel(std::ostream &output) const { preorderTravel(output, root_); } private: SPNodeType root_; SizeType size_; _Compare compare_; SPNodeType splay(SPNodeType n) { while (n && n->parent()) { if (!n->parent()->parent()) // zig step { if (n->parent()->left() == n) rightRotate(n->parent()); else leftRotate(n->parent()); } else if (n->parent()->left() == n && n->parent()->parent()->left() == n->parent()) { rightRotate(n->parent()->parent()); rightRotate(n->parent()); } else if (n->parent()->right() == n && n->parent()->parent()->right() == n->parent()) { leftRotate(n->parent()->parent()); leftRotate(n->parent()); } else if (n->parent()->right() == n && n->parent()->parent()->left() == n->parent()) { leftRotate(n->parent()); rightRotate(n->parent()); } else { rightRotate(n->parent()); leftRotate(n->parent()); } } return n; } void leftRotate(SPNodeType n) { SPNodeType right = n->right(); if (right) { n->right(right->left()); if (right->left()) right->left()->parent(n); right->parent(n->parent()); } if (n->parent() == nullptr) root_ = right; else if (n == n->parent()->left()) n->parent()->left(right); else n->parent()->right(right); if (right) right->left(n); n->parent(right); } void rightRotate(SPNodeType n) { SPNodeType left = n->left(); if (left) { n->left(left->right()); if (left->right()) left->right()->parent(n); left->parent(n->parent()); } if (n->parent() == nullptr) root_ = left; else if (n == n->parent()->left()) n->parent()->left(left); else n->parent()->right(left); if (left) left->right(n); n->parent(left); } void replace(SPNodeType old, SPNodeType new_) { if (old->parent() == nullptr) root_ = new_; else if (old == old->parent()->left()) old->parent()->left(new_); else old->parent()->right(new_); if (new_) new_->parent(old->parent()); } SPNodeType get(ConstReference value) { SPNodeType n = root_; while (n) { if (compare_(n->value(), value)) n = n->right(); else if (compare_(value, n->value())) n = n->left(); else { splay(n); return n; } } return nullptr; } SizeType height(SPNodeType n) const { if (n) return 1 + std::max(height(n->left()), height(n->right())); else return 0; } SPNodeType minimum(SPNodeType n) const { if (n) while (n->left()) n = n->left(); return n; } SPNodeType maximum(SPNodeType n) const { if (n) while (n->right()) n = n->right(); return n; } void inorderTravel(std::ostream &output, SPNodeType n) const { if (n) { inorderTravel(output, n->left()); output << n->value() << " "; inorderTravel(output, n->right()); } } void preorderTravel(std::ostream &output, SPNodeType n) const { if (n) { output << n->value() << " "; preorderTravel(output, n->left()); preorderTravel(output, n->right()); } } }; /* * // for test #include <iostream> #include <fstream> * std::fstream input, ans; * int main() { * using namespace std; * * std::shared_ptr<SplayTree<int>> st = std::make_shared<SplayTree<int>>(); * * input.open("/sample.txt"); * ans.open("/output.txt", ios::out | ios::trunc); * * int r, ty; * while (input >> r) * { * input >> ty; * * // cout << r << " " << ty << endl; * if (ty == 0) * { * st->insert(r); * } * else if (ty == 1) * { * st->erase(r); * } * else * { * st->find(r); * } * * st->preorderTravel(ans); * st->inorderTravel(ans); * ans << endl; * } * ans << st->find(0); * ans << st->height(); * ans << st->minimum(); * ans << st->maximum(); * ans << st->size(); * ans << st->empty(); * * return 0; * } * // */
code/data_structures/src/tree/multiway_tree/splay_tree/splay_tree.go
package splaytree type binaryNode struct { left, right *binaryNode item Item } type splayTree struct { root *binaryNode length int } func NewSplayTree() Tree { return &splayTree{} } func (st *splayTree) splay(item Item) { header := &binaryNode{} l, r := header, header var y *binaryNode t := st.root splaying := true for splaying { switch { case item.Less(t.item): // item might be on the left path if t.left == nil { splaying = false break } if item.Less(t.left.item) { // zig-zig -> rotate right y = t.left t.left = y.right y.right = t t = y if t.left == nil { splaying = false break } } r.left = t // link right r = t t = t.left case t.item.Less(item): // item might be on the right path if t.right == nil { splaying = false break } if t.right.item.Less(item) { // zig-zag -> rotage left y = t.right t.right = y.left y.left = t t = y if t.right == nil { splaying = false break } } l.right = t l = t t = t.right default: // found the item splaying = false } } l.right = t.left r.left = t.right t.left = header.right t.right = header.left st.root = t } func (st *splayTree) Get(key Item) Item { if st.root == nil { return nil } st.splay(key) if st.root.item.Less(key) || key.Less(st.root.item) { return nil } return st.root.item } func (st *splayTree) Has(key Item) bool { return st.Get(key) != nil } func (st *splayTree) ReplaceOrInsert(item Item) Item { panic("not implemented") } func (st *splayTree) insert(item Item) { n := &binaryNode{item: item} if st.root == nil { st.root = n return } st.splay(item) switch { case item.Less(st.root.item): n.left = st.root.left n.right = st.root st.root.left = nil case st.root.item.Less(item): n.right = st.root.right n.left = st.root st.root.right = nil default: return } st.root = n st.length++ } func (st *splayTree) Delete(item Item) Item { if st.length == 0 { return nil } st.splay(item) if st.root.item.Less(item) || item.Less(st.root.item) { return nil } // delete the root if st.root.left == nil { st.root = st.root.right } else { x := st.root.right st.root = st.root.left st.splay(item) st.root.right = x } return item } func (st *splayTree) DeleteMin() Item { if st.root == nil { return nil } x := st.root for x != nil { x = x.left } st.splay(x.item) st.Delete(x.item) return x.item } func (st *splayTree) DeleteMax() Item { if st.root == nil { return nil } x := st.root for x != nil { x = x.right } st.splay(x.item) st.Delete(x.item) return x.item } func (st *splayTree) Len() int { return st.length } func (st *splayTree) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator) { panic("not implemented") } func (st *splayTree) AscendLessThan(pivot Item, iterator ItemIterator) { panic("not implemented") } func (st *splayTree) AscendGreaterOrEqual(pivot Item, iterator ItemIterator) { panic("not implemented") }
code/data_structures/src/tree/multiway_tree/splay_tree/splay_tree.java
/* * Part of Cosmos by OpenGenus Foundation * Public API: * put(): to insert a data * size(): to get number of nodes * height(): to get height of splay tree * remove(): to remove a data * get(): to find a data */ public class SplayTree<Key extends Comparable<Key>, Value> { private Node root; private class Node { private Key key; private Value value; private Node left, right; public Node(Key key, Value value) { this.key = key; this.value = value; } } public Value get(Key key) { root = splay(root, key); int cmp = key.compareTo(root.key); if (cmp == 0) return root.value; else return null; } public void put(Key key, Value value) { if (root == null) { root = new Node(key, value); return; } root = splay(root, key); int cmp = key.compareTo(root.key); if (cmp < 0) { Node n = new Node(key, value); n.left = root.left; n.right = root; root.left = null; root = n; } else if (cmp > 0) { Node n = new Node(key, value); n.right = root.right; n.left = root; root.right = null; root = n; } else { root.value = value; } } public void remove(Key key) { if (root == null) return; root = splay(root, key); int cmp = key.compareTo(root.key); if (cmp == 0) { if (root.left == null) { root = root.right; } else { Node x = root.right; root = root.left; splay(root, key); root.right = x; } } } private Node splay(Node h, Key key) { if (h == null) return null; int cmp1 = key.compareTo(h.key); if (cmp1 < 0) { if (h.left == null) { return h; } int cmp2 = key.compareTo(h.left.key); if (cmp2 < 0) { h.left.left = splay(h.left.left, key); h = rotateRight(h); } else if (cmp2 > 0) { h.left.right = splay(h.left.right, key); if (h.left.right != null) h.left = rotateLeft(h.left); } if (h.left == null) return h; else return rotateRight(h); } else if (cmp1 > 0) { if (h.right == null) { return h; } int cmp2 = key.compareTo(h.right.key); if (cmp2 < 0) { h.right.left = splay(h.right.left, key); if (h.right.left != null) h.right = rotateRight(h.right); } else if (cmp2 > 0) { h.right.right = splay(h.right.right, key); h = rotateLeft(h); } if (h.right == null) return h; else return rotateLeft(h); } else return h; } public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } public int size() { return size(root); } private int size(Node x) { if (x == null) return 0; else return 1 + size(x.left) + size(x.right); } private Node rotateRight(Node h) { Node x = h.left; h.left = x.right; x.right = h; return x; } private Node rotateLeft(Node h) { Node x = h.right; h.right = x.left; x.left = h; return x; } public static void main(String[] args) { SplayTree<String, Integer> splay_tree = new SplayTree<String, Integer>(); splay_tree.put("OpenGenus", 1); splay_tree.put("Cosmos", 2); splay_tree.put("Vidsum", 3); splay_tree.put("Splay", 4); System.out.println("Size: " + splay_tree.size()); splay_tree.remove("Splay"); System.out.println("Size: " + splay_tree.size()); System.out.println(splay_tree.get("OpenGenus")); } }
code/data_structures/src/tree/multiway_tree/splay_tree/splay_tree.kt
// Part of Cosmos by OpenGenus Foundation /* * Public API: * get(): to find a data * put(): to insert a data * remove(): to remove a data * size: to get number of nodes * height: to get height of splay tree */ class SplayTree<KeyT : Comparable<KeyT>, ValueT>() { private inner class Node(val key: KeyT, var value: ValueT? = null) { var left: Node? = null var right: Node? = null } private var root : Node? = null var size: Int = 0 private set val height get() = height(root) private fun height(x : Node?) : Int { var result = -1 if (x != null) { result = 1 + maxOf(height(x.left), height(x.right)) } return result } private fun rotateLeft(x : Node?) : Node? { val y : Node? = x?.right x?.right = y?.left y?.left = x return y } private fun rotateRight(x : Node?) : Node? { val y : Node? = x?.left x?.left = y?.right y?.right = x return y } private fun splay(h : Node?, key : KeyT) : Node? { var root : Node = h ?: return null if (key < root.key) { val left : Node = root.left ?: return root if (key < left.key) { left.left = splay(left.left, key) root = rotateRight(root) ?: return null } else if (key > left.key) { left.right = splay(left.right, key) if (left.right != null) { root.left = rotateLeft(left) } } return if (root.left == null) root else rotateRight(root) } else if (key > root.key) { val right : Node = root.right ?: return root if (key < right.key) { right.left = splay(right.left, key) if (right.left != null) { root.right = rotateRight(right) } } else if (key > right.key) { right.right = splay(right.right, key) root = rotateLeft(root) ?: return null } return if (root.right == null) root else rotateLeft(root) } else { return root } } fun get(key: KeyT) : ValueT? { root = splay(root, key) if (root?.key == key) { return root?.value } return null } fun put(key: KeyT, value: ValueT) { if (root == null) { root = Node(key, value) size++ return } root = splay(root, key) val rootKey = root?.key ?: return if (key < rootKey) { val n = Node(key, value) n.left = root?.left n.right = root root?.left = null root = n size++ } else if (key > rootKey) { val n = Node(key, value) n.right = root?.right n.left = root root?.right = null root = n size++ } else { root?.value = value } } fun remove(key: KeyT) { root = splay(root, key) val rootKey = root?.key ?: return if (key == rootKey) { size-- if (root?.left == null) { root = root?.right } else { val x = root?.right root = root?.left splay(root, key) root?.right = x } } } } fun main(args : Array<String>) { val splay_tree = SplayTree<String, Int>() splay_tree.put("OpenGenus", 1) splay_tree.put("Cosmos", 2) splay_tree.put("Vidsum", 3) splay_tree.put("Splay", 4) println("Size Before: " + splay_tree.size) println("Height Before: " + splay_tree.height) splay_tree.remove("Splay") println("Size After: " + splay_tree.size) println("Height After: " + splay_tree.height) println(splay_tree.get("OpenGenus")) }
code/data_structures/src/tree/multiway_tree/splay_tree/splay_tree.scala
case class SplayTree[T, U](key: T, value: U, left: SplayTree[T, U], right: SplayTree[T, U]) { // Should guarantee the inserted key's node is the returned node def insert(newKey: T, newValue: U)(implicit ord: Ordering[T]): SplayTree[T, U] = { if (ord.lt(newKey, key)) { if (left == null) { SplayTree(newKey, newValue, null, this) } else { val newLeft = left.insert(newKey, newValue) newLeft.copy(right = this.copy(left = newLeft.right)) } } else if (ord.gt(newKey, key)) { if (right == null) { SplayTree(newKey, newValue, this, null) } else { val newRight = right.insert(newKey, newValue) newRight.copy(left = this.copy(right = newRight.left)) } } else { this } } // Should guarantee the get-ed key's node is the returned node def get(newKey: T)(implicit ord: Ordering[T]): Option[SplayTree[T, U]] = { if (ord.lt(newKey, key)) { if (left == null) { None } else { left.get(newKey).map { newLeft => newLeft.copy(right = this.copy(left = newLeft.right)) } } } else if (ord.gt(newKey, key)) { if (right == null) { None } else { right.get(newKey).map { newRight => newRight.copy(left = this.copy(right = newRight.left)) } } } else { Option(this) } } def inOrder(visitor: (T, U) => Unit): Unit = { if (left != null) left.inOrder(visitor); visitor(key, value) if (right != null) right.inOrder(visitor); } } object Main { def main(args: Array[String]): Unit = { val st = SplayTree("a", 100, null, null).insert("b", 2).insert("c", 3) st.inOrder((el: String, priority: Int) => println((el, priority))) st.get("b").foreach { st2 => println((st2.key, st2.value)) } st.get("b").get("c").foreach { st2 => println((st2.key, st2.value)) } st.get("b").get("c").get("a").foreach { st2 => println((st2.key, st2.value)) } } }
code/data_structures/src/tree/multiway_tree/union_find/README.md
# Union Find Description --- In computer science, a disjoint-set data structure, also called a union find data structure or merge find set, is a data structure that keeps track of a set of elements partitioned into a number of disjoint (non-overlapping) subsets. It provides near-constant-time operations (bounded by the inverse Ackermann function) to add new sets, to merge existing sets, and to determine whether elements are in the same set. In addition to many other uses (see the Applications section), disjoint-sets play a key role in Kruskal's algorithm for finding the minimum spanning tree of a graph. Union-Find API --- - union(a, b): Add connection between a and b. - connected(a, b): Return true if a and b are in the same connected component. - find(a): Find id or root of a
code/data_structures/src/tree/multiway_tree/union_find/union_find.cpp
#include <iostream> #include <vector> /* Part of Cosmos by OpenGenus Foundation */ // Union-find stores a graph, and allows two operations in amortized constant time: // * Add a new edge between two vertices. // * Check if two vertices belong to same component. class UnionFind { std::vector<size_t> parent; std::vector<size_t> rank; size_t root(size_t node) { if (parent[node] == node) return node; else return parent[node] = getParent(parent[node]); } size_t getParent(size_t node) { return parent[node]; } public: // Make a graph with `size` vertices and no edges. UnionFind(size_t size) { parent.resize(size); rank.resize(size); for (size_t i = 0; i < size; i++) { parent[i] = i; rank[i] = 1; } } // Connect vertices `a` and `b`. void Union(size_t a, size_t b) { a = root(a); b = root(b); if (a == b) return; if (rank[a] < rank[b]) parent[a] = b; else if (rank[a] > rank[b]) parent[b] = a; else { parent[a] = b; rank[b] += 1; } } // Check if vertices `a` and `b` are in the same component. bool Connected(size_t a, size_t b) { return root(a) == root(b); } }; int main() { UnionFind unionFind(10); unionFind.Union(3, 4); unionFind.Union(3, 8); unionFind.Union(0, 8); unionFind.Union(1, 3); unionFind.Union(7, 9); unionFind.Union(5, 9); // Now the components are: // 0 1 3 4 8 // 5 7 9 // 2 // 6 for (size_t i = 0; i < 10; i++) for (size_t j = i + 1; j < 10; j++) if (unionFind.Connected(i, j)) std::cout << i << " and " << j << " are in the same component" << std::endl; return 0; }
code/data_structures/src/tree/multiway_tree/union_find/union_find.go
/* Part of Cosmos by OpenGenus Foundation */ package main import "fmt" type UnionFind struct { root []int size []int } // New returns an initialized list of Size N func New(N int) *UnionFind { return new(UnionFind).init(N) } // Constructor initializes root and size arrays func (uf *UnionFind) init(N int) *UnionFind { uf = new(UnionFind) uf.root = make([]int, N) uf.size = make([]int, N) for i := 0; i < N; i++ { uf.root[i] = i uf.size[i] = 1 } return uf } // Union connects p and q by finding their roots and comparing their respective // size arrays to keep the tree flat func (uf *UnionFind) Union(p int, q int) { qRoot := uf.Root(q) pRoot := uf.Root(p) if uf.size[qRoot] < uf.size[pRoot] { uf.root[qRoot] = uf.root[pRoot] uf.size[pRoot] += uf.size[qRoot] } else { uf.root[pRoot] = uf.root[qRoot] uf.size[qRoot] += uf.size[pRoot] } } // Root or Find traverses each parent element while compressing the // levels to find the root element of p // If we attempt to access an element outside the array it returns -1 func (uf *UnionFind) Root(p int) int { if p > len(uf.root)-1 { return -1 } for uf.root[p] != p { uf.root[p] = uf.root[uf.root[p]] p = uf.root[p] } return p } // Root or Find func (uf *UnionFind) Find(p int) int { return uf.Root(p) } // Check if items p,q are connected func (uf *UnionFind) Connected(p int, q int) bool { return uf.Root(p) == uf.Root(q) } func main() { uf := New(10) uf.Union(3, 4) uf.Union(3, 8) uf.Union(0, 8) uf.Union(1, 3) uf.Union(7, 9) uf.Union(5, 9) for i := 0; i < 10; i++ { for j := i + 1; j < 10; j++ { if uf.Connected(i, j) { fmt.Printf("%d and %d are are in the same component\n", i, j) } } } }
code/data_structures/src/tree/multiway_tree/union_find/union_find.java
/* Part of Cosmos by OpenGenus Foundation */ class UnionFind { int[] parent; int[] rank; UnionFind(int size) { parent = new int[size]; rank = new int[size]; for (int i = 0; i < size; i++) { parent[i] = i; rank[i] = 0; } } public int find(int v) { if (parent[v] == v) { return v; } parent[v] = find(parent[v]); return parent[v]; } public boolean connected(int a, int b) { return find(a) == find(b); } public void union(int a, int b) { a = find(a); b = find(b); if (a != b) { if (rank[a] < rank[b]) { int tmp = a; a = b; b = tmp; } if (rank[a] == rank[b]) { rank[a]++; } parent[b] = a; } } public static void main(String[] args) { UnionFind unionFind = new UnionFind(10); unionFind.union(3, 4); unionFind.union(3, 8); unionFind.union(0, 8); unionFind.union(1, 3); unionFind.union(7, 9); unionFind.union(5, 9); // Now the components are: // 0 1 3 4 8 // 5 7 9 // 2 // 6 for (int i = 0; i < 10; i++) { for (int j = i + 1; j < 10; j++) { if (unionFind.connected(i, j)) { System.out.printf("%d and %d are in the same component\n", i, j); } } } } };
code/data_structures/src/tree/multiway_tree/union_find/union_find.js
/* Part of Cosmos by OpenGenus Foundation */ class UnionFind { constructor() { this.parents = []; this.ranks = []; } find(v) { if (this.parents[v] === v) { return v; } this.parents[v] = this.find(this.parents[v]); return this.parents[v]; } union(a, b) { if (this.parents[a] === undefined) { this.parents[a] = a; this.ranks[a] = 0; } if (this.parents[b] === undefined) { this.parents[b] = b; this.ranks[b] = 0; } a = this.find(a); b = this.find(b); if (a !== b) { if (this.ranks[a] < this.ranks[b]) { [a, b] = [b, a]; } if (this.ranks[a] === this.ranks[b]) { this.ranks[a]++; } this.parents[b] = a; } } connected(a, b) { return this.find(a) === this.find(b); } } const uf = new UnionFind(); uf.union(1, 3); uf.union(1, 4); uf.union(4, 2); uf.union(5, 6); console.log(uf.find(3)); console.log(uf.find(4)); console.log(uf.find(2)); console.log(uf.find(5));
code/data_structures/src/tree/multiway_tree/union_find/union_find.py
#!/usr/bin/env python class UnionFind: def __init__(self): self.parent = {} self.rank = {} def root(self, a): current_item = a path = [] while self.parent[current_item] != current_item: path.append(current_item) current_item = self.parent[current_item] for node in path: self.parent[node] = current_item return current_item def connected(self, a, b): return self.root(a) == self.root(b) def find(self, a): return self.root(a) def create(self, a): if a not in self.parent: self.parent[a] = a self.rank[a] = 1 def union(self, a, b): self.create(a) self.create(b) a_root = self.root(a) b_root = self.root(b) if self.rank[a_root] > self.rank[b_root]: self.parent[b_root] = a_root self.rank[a_root] += self.rank[b_root] else: self.parent[a_root] = b_root self.rank[b_root] += self.rank[a_root] def count(self, a): if a not in self.parent: return 0 return self.rank[self.root(a)] def main(): union_find = UnionFind() union_find.union(1, 3) union_find.union(1, 4) union_find.union(2, 5) union_find.union(5, 6) union_find.union(7, 8) union_find.union(7, 9) union_find.union(3, 9) for i in range(1, 10): print( "{} is in group {} with {} elements".format( i, union_find.find(i), union_find.count(i) ) ) if __name__ == "__main__": main()
code/data_structures/src/tree/multiway_tree/union_find/union_find.scala
/* Part of Cosmos by OpenGenus Foundation */ case class UnionFind[T](map: Map[T, T] = Map[T, T]()) { def add(element: T) = this.copy(map = map + (element -> element)) def find(element: T): T = { val parent = map(element) if (parent == element) element else find(parent) } private def findRank(element: T, rank: Int): (T, Int) = { val parent = map(element) if (parent == element) (element, rank) else findRank(parent, rank + 1) } def union(x: T, y: T): UnionFind[T] = { val (parentX, rankX) = findRank(x, 0) val (parentY, rankY) = findRank(y, 0) val newPair = if (rankX > rankY) (parentY -> parentX) else (parentX -> parentY) this.copy(map = map + newPair) } }
code/data_structures/src/tree/multiway_tree/union_find/union_find_dynamic.cpp
/* Part of Cosmos by OpenGenus Foundation */ // Union-find stores a graph, and allows two operations in amortized constant time: // * Add a new edge between two vertices. // * Check if two vertices belong to same component. #include <unordered_map> #include <unordered_set> #include <algorithm> // dynamic union find (elementary implementation) template<typename _ValueType, typename _Hash = std::hash<_ValueType>> class UnionFind { public: using value_type = _ValueType; UnionFind() { } // Connect vertices `a` and `b`. void merge(value_type a, value_type b) { // 1. to guarantee that the set has both `a` and `b` auto na = nodes.find(a); auto nb = nodes.find(b); if (na == nodes.end()) { nodes.insert(a); na = nodes.find(a); parents.insert({na, na}); } if (nb == nodes.end()) { nodes.insert(b); nb = nodes.find(b); parents.insert({nb, nb}); } // 2. update the map auto pa = parents.find(na); while (pa != parents.end() && pa->first != pa->second) pa = parents.find(pa->second); if (pa != parents.end()) na = pa->second; parents[na] = nb; } value_type find(value_type node) { auto root = nodes.find(node); // new node if (root == nodes.end()) { // auto it = nodes.insert(node); nodes.insert(node); auto it = nodes.find(node); parents.insert({it, it}); return node; } // existed else { auto pr = parents.find(root); while (pr != parents.end() && pr->first != pr->second) pr = parents.find(pr->second); return *(parents[root] = pr->second); } } bool connected(value_type a, value_type b) { return find(a) == find(b); } private: using Set = std::unordered_set<value_type, _Hash>; using SetIt = typename Set::iterator; struct SetItHash { size_t operator()(const SetIt& it) const { return std::hash<const int*>{} (&*it); } }; Set nodes; std::unordered_map<SetIt, SetIt, SetItHash> parents; };
code/data_structures/src/tree/multiway_tree/van_emde_boas_tree/van_emde_boas.cpp
#include <iostream> #include <math.h> using namespace std; typedef struct VEB { int u; int min, max; int count; struct VEB *summary, **cluster; } VEB; int high(int x, int u) { return (int)(x / (int) sqrt(u)); } int low(int x, int u) { return x % (int) sqrt(u); } int VEBmin(VEB*V) { return V->min; } int VEBmax(VEB*V) { return V->max; } VEB* insert(VEB*V, int x, int u) { if (!V) { V = (VEB*) malloc(sizeof(VEB)); V->min = V->max = x; V->u = u; V->count = 1; if (u > 2) { V->summary = NULL; V->cluster = (VEB**) calloc(sqrt(u), sizeof(VEB*)); } else { V->summary = NULL; V->cluster = NULL; } } else if (V->min == x || V->max == x) V->count = 1; else { if (x < V->min) { if (V->min == V->max) { V->min = x; V->count = 1; return V; } } else if (x > V->max) { int aux = V->max; V->max = x; x = aux; V->count = 1; if (V->min == x) return V; } if (V->u > 2) { if (V->cluster[high(x, V->u)] == NULL) V->summary = insert(V->summary, high(x, V->u), sqrt(V->u)); V->cluster[high(x, V->u)] = insert(V->cluster[high(x, V->u)], low(x, V->u), sqrt(V->u)); } } return V; } VEB* deleteVEB(VEB*V, int x) { if (V->min == V->max) { free(V); return NULL; } else if (x == V->min || x == V->max) { if (!--V->count) { if (V->summary) { int cluster = VEBmin(V->summary); int new_min = VEBmin(V->cluster[cluster]); V->min = cluster * (int) sqrt(V->u) + new_min; V->count = V->cluster[cluster]->count; (V->cluster[cluster])->count = 1; if ((V->cluster[cluster])->min == (V->cluster[cluster])->max) (V->cluster[cluster])->count = 1; V->cluster[cluster] = deleteVEB(V->cluster[cluster], new_min); if (V->cluster[cluster] == NULL) V->summary = deleteVEB(V->summary, cluster); } else { V->min = V->max; V->count = 1; } } } else { V->cluster[high(x, V->u)] = deleteVEB(V->cluster[high(x, V->u)], low(x, V->u)); if (V->cluster[high(x, V->u)] == NULL) V->summary = deleteVEB(V->summary, high(x, V->u)); } return V; } int elements(VEB*V, int x) { if (!V) return 0; else if (V->min == x || V->max == x) return V->count; else { if (V->cluster) return elements(V->cluster[high(x, V->u)], low(x, V->u)); else return 0; } } void printVEB(VEB*V, int u) { for (int i = 0; i < u; ++i) printf("VEB[%d] = %d\n", i, elements(V, i)); } int main() { int u = 4; int sqrt_u = sqrt(u); VEB* V = NULL; if (sqrt_u * sqrt_u != u) { printf("Invalid 'u' : Must be a perfect square\n"); return 0; } V = insert(V, 0, u); V = insert(V, 1, u); V = insert(V, 2, u); printVEB(V, u); printf("\n\n"); V = deleteVEB(V, 0); V = deleteVEB(V, 1); printVEB(V, u); return 0; }
code/data_structures/src/tree/segment_tree/LazySegmentTree.cpp
// There are generally three main function for lazy propagation in segment tree // Lazy propagation is used when we have range update query too, without it only point // update is possible. // Build function // THE SEGMENT TREE WRITTEN HERE IS FOR GETTING SUM , FOR MINIMUM, MAXIMUM, XOR AND DISTINCT ELEMENT COUNT RESPECTIVE SEGMENT TREES // CAN BE MADE JUST BY REPLACING A FEW LINES #include <bits/stdc++.h> using namespace std; typedef long long ll; const int N=1e5; int seg[4*N],lazy[4*N]; vector<int> arr; void build(int node, int st, int en) { if (st == en) { // left node ,string the single array element seg[node] = arr[st]; return; } int mid = (st + en) / 2; // recursively call for left child build(2 * node, st, mid); // recursively call for the right child build(2 * node + 1, mid + 1, en); // Updating the parent with the values of the left and right child. seg[node] = seg[2 * node] + seg[2 * node + 1]; } //Above, every node represents the sum of both subtrees below it. Build function is called once per array, and the time complexity of build() is O(N). // Update Operation function void update(int node, int st, int en, int l, int r, int val) { if (lazy[node] != 0) // if node is lazy then update it { seg[node] += (en - st + 1) * lazy[node]; if (st != en) // if its children exist then mark them lazy { lazy[2 * node] += lazy[node]; lazy[2 * node + 1] += lazy[node]; } lazy[node] = 0; // No longer lazy } if ((en < l) || (st > r)) // case 1 { return; } if (st >= l && en <= r) // case 2 { seg[node] += (en - st + 1) * val; if (st != en) { lazy[2 * node] += val; // mark its children lazy lazy[2 * node + 1] += val; } return; } // case 3 int mid = (st + en) / 2; // recursively call for updating left child update(2 * node, st, mid, l, r, val); // recursively call for updating right child update(2 * node + 1, mid + 1, en, l, r, val); // Updating the parent with the values of the left and right child. seg[node] = (seg[2 * node] + seg[2 * node + 1]); } //Here above we take care of three cases for base case: // Segment lies outside the query range: in this case, we can just simply return back and terminate the call. // Segment lies fully inside the query range: in this case, we simply update the current node and mark the children lazy. // If they intersect partially, then we all update for both the child and change the values in them. // Query function int query(int node, int st, int en, int l, int r) { /*If the node is lazy, update it*/ if (lazy[node] != 0) { seg[node] += (en - st + 1) * lazy[node]; if (st != en) //Check if the child exist { // mark both the child lazy lazy[2 * node] += lazy[node]; lazy[2 * node + 1] += lazy[node]; } // no longer lazy lazy[node] = 0; } // case 1 if (en < l || st > r) { return 0; } // case 2 if ((l <= st) && (en <= r)) { return seg[node]; } int mid = (st + en) / 2; //query left child ll q1 = query(2 * node, st, mid, l, r); // query right child ll q2 = query(2 * node + 1, mid + 1, en, l, r); return (q1 + q2); } int main(){ int n; cin >> n; arr=vector<int>(n+1); for(int i=1;i<=n;i++)cin >> arr[i]; memset(seg,0,sizeof seg); memset(lazy,0,sizeof lazy); build(1,1,n); return 0; } // As compared to non-lazy code only lazy code in base case is added. Also one should remember the kazy implementation only as it can // help u solve in non-lazy case too. // Here the insertion, query both take O(logn) time.
code/data_structures/src/tree/segment_tree/generic_segment_tree.cpp
/** * @file generic_segment_tree.cpp * @author Aryan V S (https://github.com/a-r-r-o-w) * @brief Implementation of a Generic Segment Tree */ namespace arrow { /** * @brief Support for two tree memory layouts is provided * * Binary: * - creates the segment tree as a full Binary tree * - considering the tree is built over `n` elements, the segment tree would allocate * `4.n` memory for internal usage * * EulerTour: * - more memory efficient than Binary segment tree * - considering the tree is build over `n` elements, the segment tree would allocate * `2.n` memory for internal usage * * The provided implementation defaults to Binary segment tree if no template parameter is present. */ enum class TreeMemoryLayout { Binary, EulerTour }; /** * @brief Generic Segment Tree * * A segment tree allows you to perform operations on an array in an efficient manner * * @tparam Type The type of values that the tree holds in its internal nodes * @tparam impl_type Memory layout type */ template < class Type, TreeMemoryLayout impl_type = TreeMemoryLayout::Binary > class SegmentTree { private: // Internal members maintained in the segment tree std::vector <Type> tree_; int base_size_; const std::vector <Type>& base_ref_; Type (*combine_) (const Type&, const Type&); public: /** * @brief Construct a new segment tree object * * @param base_size_ Number of leaf nodes segment tree should have (`n` in the tree_memory_layout documentation) * @param base Base of the segment tree (leaf node values) * @param combine_ Function used to combine_ values of children nodes when building parent nodes */ SegmentTree (int base_size, const std::vector <Type>& base, Type (*combine) (const Type&, const Type&)) : base_size_ (base_size), base_ref_ (base), combine_ (combine) { if constexpr (impl_type == TreeMemoryLayout::Binary) tree_.resize(4 * base_size_, Type{}); else tree_.resize(2 * base_size_, Type{}); _build_impl(0, 0, base_size_ - 1); } /** * @brief Point update in segment tree. Essentially performs `array[position] = value`. * * @param position Index to be updated * @param value Value to be set at `position` */ void pointUpdate (int position, const Type& value) { _point_update_impl(0, 0, base_size_ - 1, position, value); } /** * @brief Point query in segment tree. Essentially returns `array[position]` * * @param position Index to be queried * @return Type `array[position]` */ Type pointQuery (int position) { return _point_query_impl(0, 0, base_size_ - 1, position); } /** * @brief Range query in segment tree. Essentially performs the `combine_` function * on the range `array[l, r]` (bounds are inclusive). * * @param l Left bound of query (inclusive) * @param r Right bound of query (inclusive) * @return Type Result of the query based on `combine_` */ Type rangeQuery (int l, int r) { return _range_query_impl(0, 0, base_size_ - 1, l, r); } /** * @brief Custom point update in segment tree. * * The implementation for this method can be added by the user if they would like * to perform updates in a different sense from the norm. * * @tparam ParamTypes Types of parameters that will be passed to the update implementation * @param position Index to be updated * @param params Parameter list required by custom update implementation */ template <typename... ParamTypes> void customPointUpdate (int position, const ParamTypes&... params) { _custom_point_update_impl(0, 0, base_size_ - 1, position, params...); } /** * @brief Custom point query in segment tree. * * The implementation for this method can be added by the user if they would like * to perform updates in a different sense from the norm. * * @tparam ParamTypes Types of parameters that will be passed to the query implementation * @param position Index to be queried * @param params Parameter list required by custom query implementation */ template <typename... ParamTypes> Type customPointQuery (int position, const ParamTypes&... params) { _custom_point_query_impl(0, 0, base_size_ - 1, position, params...); } /** * @brief Custom query/update in segment tree. * * The implementation for this method can be added by the user if they would like * to perform queries in a different sense from the norm. It is very flexible with * the requirements of the user. * * This function is flexible in the sense that you can copy the body multiple times and rename * it to achieve different functionality as per liking. * * Operations like `lazy propagation` or `beats` or `persistence` have not been implemented, and * have been left to the user to do as per their liking. It can be done very easily by manipulating * the body of the _custom_query_impl method (and/or creating copies of this function with different * names for different purposes). * * @tparam ParamTypes Types of parameters that will be passed to the query/update implementation * @param params Parameter list required by custom query/update implementation */ template <typename ReturnType, typename... ParamTypes> ReturnType customQuery (const ParamTypes&... params) { return _custom_query_impl <ReturnType> (0, 0, base_size_ - 1, params...); } private: /** * @brief Returns the index of the left child given the parent index based on * chosen tree_memory_layout * * @param v Index of parent * @param tl Left bound of parent * @param tr Right bound of parent * @return int Index of left child of parent */ int _get_leftchild (int v, [[maybe_unused]] int tl, [[maybe_unused]] int tr) { if constexpr (impl_type == TreeMemoryLayout::Binary) return 2 * v + 1; else return v + 1; } /** * @brief Returns the index of the right child given the parent index based on * chosen tree_memory_layout * * @param v Index of parent * @param tl Left bound of parent * @param tr Right bound of parent * @return int Index of right child of parent */ int _get_rightchild (int v, [[maybe_unused]] int tl, [[maybe_unused]] int tr) { if constexpr (impl_type == TreeMemoryLayout::Binary) return 2 * v + 2; else { int tm = (tl + tr) / 2; int node_count = tm - tl + 1; return v + 2 * node_count; } } /** * @brief Internal function to build the segment tree * * @param v Index of node where the segment tree starts to build * @param tl Left bound of node * @param tr Right bound of node */ void _build_impl (int v, int tl, int tr) { if (tl == tr) { tree_[v] = base_ref_[tl]; return; } int tm = (tl + tr) / 2; int lchild = _get_leftchild(v, tl, tr); int rchild = _get_rightchild(v, tl, tr); _build_impl(lchild, tl, tm); _build_impl(rchild, tm + 1, tr); tree_[v] = combine_(tree_[lchild], tree_[rchild]); } /** * @brief Internal implementation of point_update * * @param v Current node index * @param tl Current node left bound * @param tr Current node right bound * @param position Index to be updated * @param value Value to be set at `position` */ void _point_update_impl (int v, int tl, int tr, int position, const Type& value) { if (tl == tr) { tree_[v] = value; return; } int tm = (tl + tr) / 2; int lchild = _get_leftchild(v, tl, tr); int rchild = _get_rightchild(v, tl, tr); // Since we need to only update a single index, we choose the correct // "side" of the segment tree to traverse to at each step if (position <= tm) _point_update_impl(lchild, tl, tm, position, value); else _point_update_impl(rchild, tm + 1, tr, position, value); tree_[v] = combine_(tree_[lchild], tree_[rchild]); } /** * @brief Internal implementation of point_query * * @param v Current node index * @param tl Current node left bound * @param tr Current node right bound * @param position Index to be updated * @return Type Value to be set at `position` */ Type _point_query_impl (int v, int tl, int tr, int position) { if (tl == tr) return tree_[v]; int tm = (tl + tr) / 2; int lchild = _get_leftchild(v, tl, tr); int rchild = _get_rightchild(v, tl, tr); // Since we need to only update a single index, we choose the correct // "side" of the segment tree to traverse to at each step if (position <= tm) return _point_query_impl(lchild, tl, tm, position); else return _point_query_impl(rchild, tm + 1, tr, position); } /** * @brief Internal implementation of rangeQuery * * @param v Current node index * @param tl Current node left bound * @param tr Current node right bound * @param l Current query left bound * @param r Current query right bound * @return Type Result of the query */ Type _range_query_impl (int v, int tl, int tr, int l, int r) { // We are out of bounds in our search // Return a sentinel value which must be defaulted in the constuctor of Type if (l > r) return {}; // We have found the correct range for the query // Return the value at current node because it's not required to process further if (tl == l and tr == r) return tree_[v]; int tm = (tl + tr) / 2; int lchild = _get_leftchild(v, tl, tr); int rchild = _get_rightchild(v, tl, tr); // We have not yet found the correct range for the query // Get results of left child and right child and combine_ Type lval = _range_query_impl(lchild, tl, tm, l, std::min(r, tm)); Type rval = _range_query_impl(rchild, tm + 1, tr, std::max(l, tm + 1), r); return combine_(lval, rval); } /** * @brief Internal implementation of customPointUpdate * * Note that you need to change the definition of this function if you're passing * any variadic argument list in customPointUpdate * * @param v Current node index * @param tl Current node left bound * @param tr Current node right bound * @param position Index to be updated */ void _custom_point_update_impl (int v, int tl, int tr, int position) { if (tl == tr) { throw std::runtime_error("undefined implementation"); return; } int tm = (tl + tr) / 2; int lchild = _get_leftchild(v, tl, tr); int rchild = _get_rightchild(v, tl, tr); // Since we need to only update a single index, we choose the correct // "side" of the segment tree to traverse to at each step if (position <= tm) _custom_point_update_impl(lchild, tl, tm, position); else _custom_point_update_impl(rchild, tm + 1, tr, position); tree_[v] = combine_(tree_[lchild], tree_[rchild]); } /** * @brief Internal implementation of customPointQuery * * Note that you need to change the definition of this function if you're passing * any variadic argument list in customPointQuery * * @param v Current node index * @param tl Current node left bound * @param tr Current node right bound * @param position Index to be queried * @return Type Result of the query */ Type _custom_point_query_impl (int v, int tl, int tr, int position) { if (tl == tr) { throw std::runtime_error("undefined implementation"); return {}; } int tm = (tl + tr) / 2; int lchild = _get_leftchild(v, tl, tr); int rchild = _get_rightchild(v, tl, tr); // Since we need to only update a single index, we choose the correct // "side" of the segment tree to traverse to at each step if (position <= tm) return _custom_point_query_impl(lchild, tl, tm, position); else return _custom_point_query_impl(rchild, tm + 1, tr, position); } /** * @brief Internal implementation of customQuery * * The user can create multiple copies with different names for this function and make * calls accordingly. Read the documentation for customQuery above. * * @tparam ReturnType Return type of the custom query/update * @param v Current node index * @param tl Current node left bound * @param tr Current node right bound * @return ReturnType Return value of the custom query/update */ template <typename ReturnType> ReturnType _custom_query_impl (int v, int tl, int tr) { if (tl == tr) { throw std::runtime_error("undefined implementation"); return ReturnType{}; } int tm = (tl + tr) / 2; int lchild = _get_leftchild(v, tl, tr); int rchild = _get_rightchild(v, tl, tr); // Change functionality as per liking if (true) return _custom_query_impl <ReturnType> (lchild, tl, tm); else return _custom_query_impl <ReturnType> (rchild, tm + 1, tr); } }; };
code/data_structures/src/tree/segment_tree/segment_tree.c
// Program to show segment tree operations like construction, query and update #include <stdio.h> #include <math.h> // A utility function to get the middle index from corner indexes. int getMid(int s, int e) { return s + (e - s)/2; } /* A recursive function to get the sum of values in given range of the array. The following are parameters for this function. st --> Pointer to segment tree index --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */ int getSumUtil(int *st, int ss, int se, int qs, int qe, int index) { // If segment of this node is a part of given range, then return the // sum of the segment if (qs <= ss && qe >= se) return st[index]; // If segment of this node is outside the given range if (se < qs || ss > qe) return 0; // If a part of this segment overlaps with the given range int mid = getMid(ss, se); return getSumUtil(st, ss, mid, qs, qe, 2*index+1) + getSumUtil(st, mid+1, se, qs, qe, 2*index+2); } /* A recursive function to update the nodes which have the given index in their range. The following are parameters st, index, ss and se are same as getSumUtil() i --> index of the element to be updated. This index is in input array. diff --> Value to be added to all nodes which have i in range */ void updateValueUtil(int *st, int ss, int se, int i, int diff, int index) { // Base Case: If the input index lies outside the range of this segment if (i < ss || i > se) return; // If the input index is in range of this node, then update the value // of the node and its children st[index] = st[index] + diff; if (se != ss) { int mid = getMid(ss, se); updateValueUtil(st, ss, mid, i, diff, 2*index + 1); updateValueUtil(st, mid+1, se, i, diff, 2*index + 2); } } // The function to update a value in input array and segment tree. // It uses updateValueUtil() to update the value in segment tree void updateValue(int arr[], int *st, int n, int i, int new_val) { // Check for erroneous input index if (i < 0 || i > n-1) { printf("Invalid Input"); return; } // Get the difference between new value and old value int diff = new_val - arr[i]; // Update the value in array arr[i] = new_val; // Update the values of nodes in segment tree updateValueUtil(st, 0, n-1, i, diff, 0); } // Return sum of elements in range from index qs (quey start) to // qe (query end). It mainly uses getSumUtil() int getSum(int *st, int n, int qs, int qe) { // Check for erroneous input values if (qs < 0 || qe > n-1 || qs > qe) { printf("Invalid Input"); return -1; } return getSumUtil(st, 0, n-1, qs, qe, 0); } // A recursive function that constructs Segment Tree for array[ss..se]. // si is index of current node in segment tree st int constructSTUtil(int arr[], int ss, int se, int *st, int si) { // If there is one element in array, store it in current node of // segment tree and return if (ss == se) { st[si] = arr[ss]; return arr[ss];Karan katyal } // If there are more than one elements, then recur for left and // right subtrees and store the sum of values in this node int mid = getMid(ss, se); st[si] = constructSTUtil(arr, ss, mid, st, si*2+1) + constructSTUtil(arr, mid+1, se, st, si*2+2); return st[si]; } /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ int *constructST(int arr[], int n) { // Allocate memory for segment tree int x = (int)(ceil(log2(n))); //Height of segment tree int max_size = 2*(int)pow(2, x) - 1; //Maximum size of segment tree int *st = new int[max_size]; // Fill the allocated memory st constructSTUtil(arr, 0, n-1, st, 0); // Return the constructed segment tree return st; } // Driver program to test above functions int main() { int arr[] = {1, 3, 5, 7, 9, 11}; int n = sizeof(arr)/sizeof(arr[0]); // Build segment tree from given array int *st = constructST(arr, n); // Print sum of values in array from index 1 to 3 printf("Sum of values in given range = %d\n", getSum(st, n, 1, 3)); // Update: set arr[1] = 10 and update corresponding segment // tree nodes updateValue(arr, st, n, 1, 10); // Find sum after the value is updated printf("Updated sum of values in given range = %d\n", getSum(st, n, 1, 3)); return 0; }
code/data_structures/src/tree/segment_tree/segment_tree.java
class SegmentTree { private int seg_t[]; // An array to store the segment tree implementation /** * Constructor which takes the size of the array and the array as a parameter and constructs the segment tree * @author Kanakalatha Vemuru (https://github.com/KanakalathaVemuru) * @param n is the size of the array * @param arr is the array on which segment tree has to be constructed */ public SegmentTree(int n, int arr[]) { int x = (int) (Math.ceil(Math.log(n) / Math.log(2))); int seg_size = 2 * (int) Math.pow(2, x) - 1; this.seg_t = new int[seg_size]; constructTree(arr, 0, n - 1, 0); } /** A function which will create the segment tree * @author Kanakalatha Vemuru (https://github.com/KanakalathaVemuru) * @param arr the array on which segment tree has to be constructed * @param start an integer representing the start of the segment represented by current node * @param end an integer representing the end of the segment represented by current node * @param index the integer representing the index of current node in segment tree * @return an integer representing the sum of the current segment */ public int constructTree(int[] arr, int start, int end, int index) { if (start == end) { this.seg_t[index] = arr[start]; return arr[start]; } int mid = start + (end - start) / 2; this.seg_t[index] = constructTree(arr, start, mid, index*2 + 1) + constructTree(arr, mid + 1, end, index*2 + 2); return this.seg_t[index]; } /** A function which will update the value at a index i. This will be called by the update function internally * @author Kanakalatha Vemuru (https://github.com/KanakalathaVemuru) * @param start an integer representing the start of the segment represented by current node * @param end an integer representing the end of the segment represented by current node * @param index an integer representing the index whose value has to be updated in the array * @param diff the difference between the value of previous value and updated value * @param seg_index the integer representing the index of current node in segment tree */ private void updateValueUtil(int start, int end, int index, int diff, int seg_index) { if (index < start || index > end) { return; } this.seg_t[seg_index] += diff; if (start != end) { int mid = start + (end - start) / 2; updateValueUtil(start, mid, index, diff, seg_index*2 + 1); updateValueUtil(mid + 1, end, index, diff, seg_index*2 + 2); } } /** A function to update the value at a particular index * @author Kanakalatha Vemuru (https://github.com/KanakalathaVemuru) * @param n is the size of the array * @param arr is the array on which segment tree has to be constructed * @param index the integer representing the index whose value to be updated * @param value the integer representing the updated value */ public void updateValue(int[] arr, int n, int index, int value) { if (index < 0 || index > n) { return; } int diff = value - arr[index]; arr[index] = value; updateValueUtil(0, n - 1, index, diff, 0); } /** A function to get the sum of the elements from index q_start to index q_end. This will be called internally * @author Kanakalatha Vemuru (https://github.com/KanakalathaVemuru) * @param start an integer representing the start of the segment represented by current node * @param end an integer representing the end of the segment represented by current node * @param q_start an integer representing the start of the segment whose sum we are quering * @param q_end an integer representing the end of the segment whose sum we are quering * @param seg_index the integer representing the index of current node in segment tree * @return an integer representing the sum of the segment q_start to q_end */ private int getSumUtil(int start, int end, int q_start, int q_end, int seg_index) { if (q_start <= start && q_end >= end) { return this.seg_t[seg_index]; } if (q_start > end || q_end < start) { return 0; } int mid = start + (end - start)/2; return getSumUtil(start, mid, q_start, q_end, seg_index*2 + 1) + getSumUtil(mid + 1, end, q_start, q_end, seg_index*2 + 2); } /** A function to query the sum of the segment [start...end] * @author Kanakalatha Vemuru (https://github.com/KanakalathaVemuru) * @param n an integer representing the length of the array * @param start an integer representing the start of the segment whose sum we are quering * @param end an integer representing the end of the segment whose sum we are quering * @return an integer representing the sum of the segment start to end */ public int getSum(int n, int start, int end) { if (start < 0 || end > n || start > end) { return 0; } return getSumUtil(0, n-1, start, end, 0); } // Driver program for testing public static void main(String args[]) { int arr[] = {1, 3, 5, 7, 9, 11}; int n = arr.length; SegmentTree st = new SegmentTree(n, arr); // Print sum of values in array from index 1 to 3 System.out.println("Sum of values in given range = " + st.getSum(n, 1, 3) + ".\n"); // Update: set arr[1] = 10 and update corresponding segment // tree nodes st.updateValue(arr, n, 1, 10); // Find sum after the value is updated System.out.println("Updated sum of values in given range = " + st.getSum(n, 1, 3) + ".\n"); } }
code/data_structures/src/tree/segment_tree/segment_tree_optimized.cpp
// Program to show optimised segment tree operations like construction, sum query and update #include <iostream> using namespace std; /*Parameters for understanding code easily: N = size of the array for which we are making the segment tree arr= Given array, it can be of any size tree=Array for the segment tree representation*/ void createTreeOp(int *arr, int *tree, int size) { // First the array elements are fixed in the tree array from N index to 2N-1 index for (int i = size; i < 2 * size; i++) { tree[i] = arr[i - size]; } // Now tree elements are inserted by taking sum of nodes on children index from index N-1 to 1 for (int i = size - 1; i > 0; i--) { tree[i] = tree[2 * i] + tree[2 * i + 1]; } // This approach only requires atmost 2N elements to make segment tree of N sized array } int sumOp(int *tree, int start, int end, int size) { start += size; end += size; int sum = 0; /*Range is set [size+start,size+end] in the beginning. At each step range is moved up and the value do not belonging to higher range are added.*/ while (start <= end) { if (start % 2 == 1) { sum += tree[start++]; } if (end % 2 == 0) { sum += tree[end--]; } start = start / 2; end = end / 2; } return sum; } void update(int *tree, int index, int size, int newVal) { index = size + index; int incr = newVal - tree[index]; // First calculate the increase in the value required in the element after the updating while (index >= 1) { tree[index] += incr; index = index / 2; } // Loop to increment the value incr in the path from root to required indexed leaf node } int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int *tree = new int[20]; /* In this approach we only require 2N sized tree array for storing the segment tree and all the operations can be achieved in iterative methods.*/ createTreeOp(arr, tree, 10); cout<<"SEGMENT TREE"<<endl; for (int i = 1; i < 20; i++) { cout << tree[i] << " "; } cout << endl<<endl; cout <<"The sum of the segment from index to 3 to 5 "<<sumOp(tree, 3, 5, 10)<<endl; update(tree, 0, 10, -1); cout <<"Updating the value at index 0 with -1"<<endl; cout<<endl<<"SEGMENT TREE"<<endl; for (int i = 1; i < 20; i++) { cout << tree[i] << " "; } }
code/data_structures/src/tree/segment_tree/segment_tree_rmq.adb
with Ada.Integer_Text_IO, Ada.Text_IO; use Ada.Integer_Text_IO, Ada.Text_IO; -- Compile: -- gnatmake segment_Tree_rmq procedure segment_Tree_rmq is INT_MAX: constant integer := 999999; MAXN : constant integer := 100005; v : array(0..MAXN) of integer; tree: array(0..4*MAXN) of integer; n : integer; q : integer; a : integer; b : integer; c : integer; function min(a: integer; b: integer) return integer is begin if a < b then return a; else return b; end if; end min; procedure build(node: integer; l: integer; r: integer) is mid: integer; begin mid := (l + r)/2; if l = r then tree(node) := v(l); return; end if; build(2 * node, l, mid); build(2*node+1,mid+1,r); tree(node) := min( tree(2*node), tree(2*node + 1)); end build; --Update procedure procedure update(node: integer; l: integer; r: integer; pos: integer; val: integer) is mid: integer := (l + r)/2; begin if l > pos or r < pos or l > r then return; end if; if(l = r) then tree(node) := val; return; end if; if pos <= mid then update(2*node,l,mid,pos,val); else update(2*node+1,mid+1,r,pos,val); end if; tree(node) := min( tree(2*node), tree(2*node + 1)); end update; --Query function function query(node : integer; l: integer; r: integer; x: integer; y: integer) return integer is mid: integer := (l + r)/2; p1: integer; p2: integer; begin if l > r or l > y or r < x then return INT_MAX; end if; if x <= l and r <= y then return tree(node); end if; p1 := query(2*node,l,mid,x,y); p2 := query(2*node+1,mid+1,r,x,y); if p1 = INT_MAX then return p2; end if; if p2 = INT_MAX then return p1; end if; return min(p1, p2); end query; begin Put_Line("Input the array range"); Get(n); Put_Line("Input the values"); for i in 1..n loop Get(v(i)); end loop; build(1,0,n-1); Put_Line("Input the number of operations"); Get(q); while q > 0 loop Put_Line("Input 0 to query and 1 to update"); Get(a); Put_Line("Input the STARTING index of the query range"); Get(b); Put_Line("Input the ENDING index of the query range"); Get(c); if a = 0 then Put_Line("Minimum value of the given range"); Put(query(1,1,n,b,c)); Put_Line(""); elsif a = 1 then update(1,1,n,b,c); else Put_Line("Invalid Operation"); q := q + 1; end if; q := q - 1; end loop; end segment_Tree_rmq;
code/data_structures/src/tree/space_partitioning_tree/interval_tree/README.md
# Cosmos Collaborative effort by [OpenGenus](https://github.com/OpenGenus/cosmos)
code/data_structures/src/tree/space_partitioning_tree/interval_tree/interval_tree.cpp
//Part of Cosmos by OpenGenus Foundation #include <iostream> using namespace std; struct Interval { int low, high; }; struct ITNode { Interval *i; int max; ITNode *left, *right; }; ITNode * newNode(Interval i) { ITNode *temp = new ITNode; temp->i = new Interval(i); temp->max = i.high; temp->left = temp->right = NULL; return temp; }; ITNode *insert(ITNode *root, Interval i) { if (root == NULL) return newNode(i); int l = root->i->low; if (i.low < l) root->left = insert(root->left, i); else root->right = insert(root->right, i); if (root->max < i.high) root->max = i.high; return root; } bool doOVerlap(Interval i1, Interval i2) { if (i1.low <= i2.high && i2.low <= i1.high) return true; return false; } Interval *overlapSearch(ITNode *root, Interval i) { if (root == NULL) return NULL; if (doOVerlap(*(root->i), i)) return root->i; if (root->left != NULL && root->left->max >= i.low) return overlapSearch(root->left, i); return overlapSearch(root->right, i); } void inorder(ITNode *root) { if (root == NULL) return; inorder(root->left); cout << "[" << root->i->low << ", " << root->i->high << "]" << " max = " << root->max << endl; inorder(root->right); } int main() { Interval ints[] = {{15, 20}, {10, 30}, {17, 19}, {5, 20}, {12, 15}, {30, 40} }; int n = sizeof(ints) / sizeof(ints[0]); ITNode *root = NULL; for (int i = 0; i < n; i++) root = insert(root, ints[i]); cout << "Inorder traversal of constructed Interval Tree is\n"; inorder(root); Interval x = {6, 7}; cout << "\nSearching for interval [" << x.low << "," << x.high << "]"; Interval *res = overlapSearch(root, x); if (res == NULL) cout << "\nNo Overlapping Interval"; else cout << "\nOverlaps with [" << res->low << ", " << res->high << "]"; return 0; }