filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/data_structures/src/stack/infix_to_postfix/infix_to_postfix.cpp
#include <stdio.h> #include <string.h> #include <stdlib.h> // Part of Cosmos by OpenGenus Foundation // Stack type struct Stack { int top; unsigned capacity; int* array; }; // Stack Operations struct Stack* createStack( unsigned capacity ) { struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack)); if (!stack) return NULL; stack->top = -1; stack->capacity = capacity; stack->array = (int*) malloc(stack->capacity * sizeof(int)); if (!stack->array) return NULL; return stack; } int isEmpty(struct Stack* stack) { return stack->top == -1; } char peek(struct Stack* stack) { return stack->array[stack->top]; } char pop(struct Stack* stack) { if (!isEmpty(stack)) return stack->array[stack->top--]; return '$'; } void push(struct Stack* stack, char op) { stack->array[++stack->top] = op; } // A utility function to check if the given character is operand int isOperand(char ch) { return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'); } // A utility function to return precedence of a given operator // Higher returned value means higher precedence int Prec(char ch) { switch (ch) { case '+': case '-': return 1; case '*': case '/': return 2; case '^': return 3; } return -1; } // The main function that converts given infix expression // to postfix expression. int infixToPostfix(char* exp) { int i, k; // Create a stack of capacity equal to expression size struct Stack* stack = createStack(strlen(exp)); if (!stack) // See if stack was created successfully return -1; for (i = 0, k = -1; exp[i]; ++i) { // If the scanned character is an operand, add it to output. if (isOperand(exp[i])) exp[++k] = exp[i]; // If the scanned character is an ‘(‘, push it to the stack. else if (exp[i] == '(') push(stack, exp[i]); // If the scanned character is an ‘)’, pop and output from the stack // until an ‘(‘ is encountered. else if (exp[i] == ')') { while (!isEmpty(stack) && peek(stack) != '(') exp[++k] = pop(stack); if (!isEmpty(stack) && peek(stack) != '(') return -1; // invalid expression else pop(stack); } else // an operator is encountered { while (!isEmpty(stack) && Prec(exp[i]) <= Prec(peek(stack))) exp[++k] = pop(stack); push(stack, exp[i]); } } // pop all the operators from the stack while (!isEmpty(stack)) exp[++k] = pop(stack ); exp[++k] = '\0'; printf( "%sn", exp ); return 0; } // Driver program to test above functions int main() { char exp[] = "a+b*(c^d-e)^(f+g*h)-i"; infixToPostfix(exp); return 0; }
code/data_structures/src/stack/infix_to_postfix/infix_to_postfix.java
import java.util.Scanner; import java.util.Stack; public class InfixToPostfix { /** * Checks if the input is operator or not * @param c input to be checked * @return true if operator */ private boolean isOperator(char c){ if(c == '+' || c == '-' || c == '*' || c =='/' || c == '^') return true; return false; } /** * Checks if c2 has same or higher precedence than c1 * @param c1 first operator * @param c2 second operator * @return true if c2 has same or higher precedence */ private boolean checkPrecedence(char c1, char c2){ if((c2 == '+' || c2 == '-') && (c1 == '+' || c1 == '-')) return true; else if((c2 == '*' || c2 == '/') && (c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/')) return true; else if((c2 == '^') && (c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/')) return true; else return false; } /** * Converts infix expression to postfix * @param infix infix expression to be converted * @return postfix expression */ public String convert(String infix){ System.out.printf("%-8s%-10s%-15s\n", "Input","Stack","Postfix"); String postfix = ""; //equivalent postfix is empty initially Stack<Character> s = new Stack<>(); //stack to hold symbols s.push('#'); //symbol to denote end of stack System.out.printf("%-8s%-10s%-15s\n", "",format(s.toString()),postfix); for(int i = 0; i < infix.length(); i++){ char inputSymbol = infix.charAt(i); //symbol to be processed if(isOperator(inputSymbol)){ //if a operator //repeatedly pops if stack top has same or higher precedence while(checkPrecedence(inputSymbol, s.peek())) postfix += s.pop(); s.push(inputSymbol); } else if(inputSymbol == '(') s.push(inputSymbol); //push if left parenthesis else if(inputSymbol == ')'){ //repeatedly pops if right parenthesis until left parenthesis is found while(s.peek() != '(') postfix += s.pop(); s.pop(); } else postfix += inputSymbol; System.out.printf("%-8s%-10s%-15s\n", ""+inputSymbol,format(s.toString()),postfix); } //pops all elements of stack left while(s.peek() != '#'){ postfix += s.pop(); System.out.printf("%-8s%-10s%-15s\n", "",format(s.toString()),postfix); } return postfix; } /** * Formats the input stack string * @param s It is a stack converted to string * @return formatted input */ private String format(String s){ s = s.replaceAll(",",""); //removes all , in stack string s = s.replaceAll(" ",""); //removes all spaces in stack string s = s.substring(1, s.length()-1); //removes [] from stack string return s; } public static void main(String[] args) { InfixToPostfix obj = new InfixToPostfix(); Scanner sc = new Scanner(System.in); System.out.print("Infix : \t"); String infix = sc.next(); System.out.print("Postfix : \t"+obj.convert(infix)); } }
code/data_structures/src/stack/infix_to_postfix/infix_to_postfix.py
# Part of Cosmos by OpenGenus Foundation class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items) - 1] def size(self): return len(self.items) def infix_to_postfix(exp): prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 s = Stack() postfix_list = [] token_list = exp.split() for i in token_list: if i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or i in "1234567890": postfix_list.append(i) elif i == "(": s.push(i) elif i == ")": top_token = s.pop() while top_token != "(": postfix_list.append(top_token) top_token = s.pop() else: while (not s.is_empty()) and (prec[s.peek()] >= prec[i]): postfix_list.append(s.pop()) s.push(i) while not s.is_empty(): postfix_list.append(s.pop()) return " ".join(postfix_list) print(infix_to_postfix("A * B + C * D")) print(infix_to_postfix("( A + B ) * C - ( D - E ) * ( F + G )"))
code/data_structures/src/stack/infix_to_postfix/infix_to_postfix2.cpp
#include <iostream> #include <stack> class InfixToPostfix { public: InfixToPostfix(const std::string &expression) : expression_(expression) {} int getPrecedenceOfOperators(char); std::string convertInfixToPostfix(); private: std::string expression_; }; int InfixToPostfix::getPrecedenceOfOperators(char ch) { if (ch == '+' || ch == '-') return 1; if (ch == '*' || ch == '/') return 2; if (ch == '^') return 3; else return 0; } std::string InfixToPostfix::convertInfixToPostfix() { std::stack <char> stack1; std::string infixToPostfixExp = ""; int i = 0; while (expression_[i] != '\0') { //if scanned character is open bracket push it on stack if (expression_[i] == '(' || expression_[i] == '[' || expression_[i] == '{') stack1.push(expression_[i]); //if scanned character is opened bracket pop all literals from stack till matching open bracket gets poped else if (expression_[i] == ')' || expression_[i] == ']' || expression_[i] == '}') { if (expression_[i] == ')') { while (stack1.top() != '(') { infixToPostfixExp = infixToPostfixExp + stack1.top(); stack1.pop(); } } if (expression_[i] == ']') { while (stack1.top() != '[') { infixToPostfixExp = infixToPostfixExp + stack1.top(); stack1.pop(); } } if (expression_[i] == '}') { while (stack1.top() != '{') { infixToPostfixExp = infixToPostfixExp + stack1.top(); stack1.pop(); } } stack1.pop(); } //if scanned character is operator else if (expression_[i] == '+' || expression_[i] == '-' || expression_[i] == '*' || expression_[i] == '/' || expression_[i] == '^') { //very first operator of expression is to be pushed on stack if (stack1.empty()) { stack1.push(expression_[i]); } else{ /* * check the precedence order of instack(means the one on top of stack) and incoming operator, * if instack operator has higher priority than incoming operator pop it out of stack&put it in * final postifix expression, on other side if precedence order of instack operator is less than i * coming operator, push incoming operator on stack. */ if (getPrecedenceOfOperators(stack1.top()) >= getPrecedenceOfOperators(expression_[i])) { infixToPostfixExp = infixToPostfixExp + stack1.top(); stack1.pop(); stack1.push(expression_[i]); } else { stack1.push(expression_[i]); } } } else { //if literal is operand, put it on to final postfix expression infixToPostfixExp = infixToPostfixExp + expression_[i]; } i++; } //poping out all remainig operator literals & adding to final postfix expression if (!stack1.empty()) { while (!stack1.empty()) { infixToPostfixExp = infixToPostfixExp + stack1.top(); stack1.pop(); } } return infixToPostfixExp; } int main() { std::string expr; std::cout << "\nEnter the Infix Expression : "; std::cin >> expr; InfixToPostfix p(expr); std::cout << "\nPostfix expression : " << p.convertInfixToPostfix(); }
code/data_structures/src/stack/infix_to_prefix/README.md
# What are Prefix Notations? Polish notation (PN), also known as Normal Polish notation (NPN), Łukasiewicz notation, Warsaw notation, Polish prefix notation or simply prefix notation, is a mathematical notation in which operators precede their operands, in contrast to the more common infix notation, in which operators are placed between operands, as well as reverse Polish notation (RPN), in which operators follow their operands. # Application Prefix and Postfix notations are applied by computers while solving an expression, by converting that expression into either of those forms. # Steps in converting Infix to Prefix At first infix expression is reversed. Note that for reversing the opening and closing parenthesis will also be reversed. ``` for an example: The expression: A + B * (C - D) after reversing the expression will be: ) D – C ( * B + A ``` **so we need to convert opening parenthesis to closing parenthesis and vice versa.** After reversing, the expression is converted to postfix form by using infix to postfix algorithm. After that again the postfix expression is reversed to get the prefix expression. # Algorithm * Push “)” onto STACK, and add “(“ to end of the A * Scan A from right to left and repeat step 3 to 6 for each element of A until the STACK is empty * If an operand is encountered add it to B * If a right parenthesis is encountered push it onto STACK * If an operator is encountered then: * Repeatedly pop from STACK and add to B each operator (on the top of STACK) which has same or higher precedence than the operator. * Add operator to STACK * If left parenthesis is encountered then * Repeatedly pop from the STACK and add to B (each operator on top of stack until a left parenthesis is encounterd) * Remove the left parenthesis * Exit
code/data_structures/src/stack/infix_to_prefix/infix_to_prefix.cpp
// Including Library #include <iostream> #include <ctype.h> #include <string.h> #include <stack> /** Function to check if given character is an operator or not. **/ bool isOperator(char c) { return (!isalpha(c) && !isdigit(c)); } /** Function to find priority of given operator.**/ int getPriority(char c) { if (c == '-' || c == '+') return 1; else if (c == '*' || c == '/') return 2; else if (c == '^') return 3; return 0; } /** Function that converts infix expression to prefix expression. **/ std::string infixToPrefix(std::string infix) { // stack for operators. std::stack<char> operators; // stack for operands. std::stack<std::string> operands; for (int i = 0; i < infix.length(); i++) { /** If current character is an opening bracket, then push into the operators stack. **/ if (infix[i] == '(') operators.push(infix[i]); /** If current character is a closing bracket, then pop from both stacks and push result in operands stack until matching opening bracket is not found. **/ else if (infix[i] == ')') { while (!operators.empty() && operators.top() != '(') { // operand 1 std::string op1 = operands.top(); operands.pop(); // operand 2 std::string op2 = operands.top(); operands.pop(); // operator char op = operators.top(); operators.pop(); /** Add operands and operator in form operator + operand1 + operand2. **/ std::string tmp = op + op2 + op1; operands.push(tmp); } /** Pop opening bracket from stack. **/ operators.pop(); } /** If current character is an operand then push it into operands stack. **/ else if (!isOperator(infix[i])) operands.push(std::string(1, infix[i])); /** If current character is an operator, then push it into operators stack after popping high priority operators from operators stack and pushing result in operands stack. **/ else { while (!operators.empty() && getPriority(infix[i]) <= getPriority(operators.top())) { std::string op1 = operands.top(); operands.pop(); std::string op2 = operands.top(); operands.pop(); char op = operators.top(); operators.pop(); std::string tmp = op + op2 + op1; operands.push(tmp); } operators.push(infix[i]); } } /** Pop operators from operators stack until it is empty and add result of each pop operation in operands stack. **/ while (!operators.empty()) { std::string op1 = operands.top(); operands.pop(); std::string op2 = operands.top(); operands.pop(); char op = operators.top(); operators.pop(); std::string tmp = op + op2 + op1; operands.push(tmp); } /** Final prefix expression is present in operands stack. **/ return operands.top(); } // Driver code int main() { std::string s; std::cin >> s; std::cout << infixToPrefix(s); return 0; } // Input - (A-B/C)*(A/K-L) // Output - *-A/BC-/AKL
code/data_structures/src/stack/infix_to_prefix/infix_to_prefix.java
// To include java library import java.util.*; public class infixPrefix { /** * This method checks if given character is * an operator or not. * @param c character input */ static boolean isOperator(char c) { return (!(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && !(c >= 'A' && c <= 'Z')); } /** * This method checks priority of given operator. * @param c character input */ static int getPriority(char C) { if (C == '-' || C == '+') return 1; else if (C == '*' || C == '/') return 2; else if (C == '^') return 3; return 0; } /** * This method converts infix * expression to prefix expression. * @param infix string input */ static String infixToPrefix(String infix) { // stack for operators. Stack<Character> operators = new Stack<Character>(); // stack for operands. Stack<String> operands = new Stack<String>(); for (int i = 0; i < infix.length(); i++) { // If current character is an // opening bracket, then // push into the operators stack. if (infix.charAt(i) == '(') { operators.push(infix.charAt(i)); } // If current character is a // closing bracket, then pop from // both stacks and push result // in operands stack until // matching opening bracket is // not found. else if (infix.charAt(i) == ')') { while (!operators.empty() && operators.peek() != '(') { // operand 1 String op1 = operands.peek(); operands.pop(); // operand 2 String op2 = operands.peek(); operands.pop(); // operator char op = operators.peek(); operators.pop(); // Add operands and operator // in form operator + // operand1 + operand2. String tmp = op + op2 + op1; operands.push(tmp); } // Pop opening bracket // from stack. operators.pop(); } // If current character is an // operand then push it into // operands stack. else if (!isOperator(infix.charAt(i))) { operands.push(infix.charAt(i) + ""); } // If current character is an // operator, then push it into // operators stack after popping // high priority operators from // operators stack and pushing // result in operands stack. else { while (!operators.empty() && getPriority(infix.charAt(i)) <= getPriority(operators.peek())) { String op1 = operands.peek(); operands.pop(); String op2 = operands.peek(); operands.pop(); char op = operators.peek(); operators.pop(); String tmp = op + op2 + op1; operands.push(tmp); } operators.push(infix.charAt(i)); } } // Pop operators from operators // stack until it is empty and // operation in add result of // each pop operands stack. while (!operators.empty()) { String op1 = operands.peek(); operands.pop(); String op2 = operands.peek(); operands.pop(); char op = operators.peek(); operators.pop(); String tmp = op + op2 + op1; operands.push(tmp); } // Final prefix expression is // present in operands stack. return operands.peek(); } } // Driver Code public class infixConversion { public static void main(String args[]) { infixPrefix g = new infixPrefix(); // Using Scanner for Getting Input from User Scanner in = new Scanner(System.in); String s = in.nextLine(); // String s = "(A-B/C)*(A/K-L)"; System.out.println(g.infixToPrefix(s)); } } // Input - (A-B/C)*(A/K-L) // Output - *-A/BC-/AKL
code/data_structures/src/stack/postfix_evaluation/README.md
# Stack Description --- Stacks are an abstract data type (ADT) that function to store and manipulate data. Their order is last-in-first-out (LIFO). To implement a stack, an array or [linked list](../linked_list) can be used. A stack is similar to a [Tower of Hanoi](https://en.wikipedia.org/wiki/Tower_of_Hanoi) in that the first object pushed onto the stack cannot be removed until every other object pushed on top of it has also been removed. It is also similar to a stack of plates in a cafeteria, where the bottom plate cannot be removed until all of the plates above it have been removed as well. Functions --- - Pop() --Removes an item from the stack - Push() --Adds an item to the stack - Peek() --Returns the top element of the stack - isEmpty() --Returns true if the stack is empty Time Complexity --- All the functions are O(1). ![visualization](https://ssodelta.files.wordpress.com/2014/10/stack.png)
code/data_structures/src/stack/postfix_evaluation/postfix_evaluation.c
#include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> // Stack type struct Stack { int top; unsigned capacity; int* array; }; // Stack Operations struct Stack* createStack( unsigned capacity ) { struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack)); if (!stack) return NULL; stack->top = -1; stack->capacity = capacity; stack->array = (int*) malloc(stack->capacity * sizeof(int)); if (!stack->array) return NULL; return stack; } int isEmpty(struct Stack* stack) { return stack->top == -1 ; } char peek(struct Stack* stack) { return stack->array[stack->top]; } char pop(struct Stack* stack) { if (!isEmpty(stack)) return stack->array[stack->top--] ; return '$'; } void push(struct Stack* stack, char op) { stack->array[++stack->top] = op; } // The main function that returns value of a given postfix expression int evaluatePostfix(char* exp) { // Create a stack of capacity equal to expression size struct Stack* stack = createStack(strlen(exp)); int i; // See if stack was created successfully if (!stack) return -1; // Scan all characters one by one for (i = 0; exp[i]; ++i) { // If the scanned character is an operand (number here), // push it to the stack. if (isdigit(exp[i])) push(stack, exp[i] - '0'); // If the scanned character is an operator, pop two // elements from stack apply the operator else { int val1 = pop(stack); int val2 = pop(stack); switch (exp[i]) { case '+': push(stack, val2 + val1); break; case '-': push(stack, val2 - val1); break; case '*': push(stack, val2 * val1); break; case '/': push(stack, val2/val1); break; } } } return pop(stack); } // Driver program to test above functions int main() { char exp[] = "231*+9-"; printf ("Value of %s is %d", exp, evaluatePostfix(exp)); return 0; }
code/data_structures/src/stack/postfix_evaluation/postfix_evaluation.cpp
/* In this Input will be Postfix Expression on which particular operations will be performed using stacks and output will be the result of that expression. Eg. Input => 4 6 + 2 / 5 * 7 + Output => 32 Evaluation =>((((4+6)/2)*5)+7) = 32 */ //code by Sanskruti Shahu #include<bits/stdc++.h> using namespace std; int postfixEval (string s) { stack<int> st; int operand1,operand2; for(int i=0;i<s.size();i++) { if(s[i]>=48) { st.push(s[i]-48); } else { operand2=st.top(); st.pop(); operand1=st.top(); st.pop(); if(s[i]=='+') { st.push(operand1+operand2); } else if(s[i]=='-') { st.push(operand1-operand2); } else if(s[i]=='*') { st.push(operand1*operand2); } else if(s[i]=='/') { st.push(operand1/operand2); } else if(s[i]=='^') { st.push(operand1^operand2); } } } return st.top(); } int main() { string s; cin>>s; cout<<"Result = "<<postfixEval(s)<<endl; } /* Time Complexity is O(n). (where n is length of string) Space Complexity is O(1) */
code/data_structures/src/stack/postfix_evaluation/postfix_evaluation.java
// Part of Cosmos by OpenGenus // Java proram to evaluate value of a postfix expression import java.util.Scanner; import java.util.Stack; public class Evaluate { // Method to evaluate value of a postfix expression static int evaluatePostfix(String s) { //create a stack Stack<Integer> stack=new Stack<>(); // Scan all characters one by one for(int i=0;i<s.length();i++) { char c=s.charAt(i); // If the scanned character is an operand (number here), // push it to the stack. if(Character.isDigit(c)) stack.push(c - '0'); // If the scanned character is an operator, pop two // elements from stack apply the operator else { int a = stack.pop(); int b = stack.pop(); switch(c) { case '+': stack.push(b+a); break; case '-': stack.push(b-a); break; case '/': stack.push(b/a); break; case '*': stack.push(b*a); break; } } } return stack.pop(); } // Driver program to test above functions public static void main(String[] args) { Scanner sc=new Scanner(); String s=sc.next(); System.out.println(evaluatePostfix(s)); } /* Input : 231*+9- Output : -4 */ }
code/data_structures/src/stack/postfix_evaluation/postfix_evaluation.py
# special feature verbose mode -> to trace what is happening import sys class postfix: def __init__(self, verbose=False): self._stack = [] self._verbose = verbose pass def evaluate(self, post_fix_string): if self._verbose: print("[!] Postfix Evaluation Started For :", post_fix_string) for x in post_fix_string: try: self._stack.append(int(x)) if self._verbose: print("[!] Pushed ", x, " in stack -> ", self._stack) except ValueError: self._act(x) if self._verbose: print("[!] Answer is : ", self._stack[0]) return self._stack[0] else: return self._stack[0] def _act(self, operand): b = self._stack.pop() a = self._stack.pop() if self._verbose: print( "[!] Popped last two values from stack, a = {} and b = {} -> ".format( a, b ), self._stack, ) if operand == "+": self._stack.append(a + b) if self._verbose: print( "[!] Performed {} + {} and Pushed in stack -> ".format(a, b), self._stack, ) elif operand == "/": try: self._stack.append(a // b) if self._verbose: print( "[!] Performed {} // (integer division) {} and Pushed in stack -> ".format( a, b ), self._stack, ) except ZeroDivisionError: if self._verbose: print( "[x] Error : Divide By Zero at a = {} and b = {} with current stack state -> ".format( a, b ), self._stack, ) sys.exit(1) elif operand == "-": self._stack.append(a - b) if self._verbose: print( "[!] Performed {} - {} and Pushed in stack -> ".format(a, b), self._stack, ) elif operand == "*": self._stack.append(a * b) if self._verbose: print( "[!] Performed {} * {} and Pushed in stack -> ".format(a, b), self._stack, ) pass pass p_fix1 = postfix() p_fix2 = postfix(verbose=True) # with verbose mode print("------ Without Verbose Mode ------") print("Answer is", p_fix1.evaluate("12+3*1-")) print("\n\n------ With Verbose Mode ------") p_fix2.evaluate("1234+-/2+0/3-") # raising exception intentionally
code/data_structures/src/stack/postfix_evaluation/postfix_evaluation.sh
#!/bin/bash #Read the Expression read -p "Enter The Exppression " EX #Here q variable will act as top pointer in stack pointing to topmost element q=-1 #cnt variable will count so that we an read each character cnt=1 #Here re is the variable for regular expression check re='^-?[0-9]+([.][0-9]+)?$' #function to make required calculations function calculate(){ upr=${arr[q]} k=$[$q-1] lwr=${arr[k]} res=$[$lwr $c $upr] arr[k]=$res q=$k } #Here The operations are performed while : do c=`echo "$EX"|cut -d " " -f "$cnt"` #Here check if length of c is nonzero if [[ -n $c ]] then #Here c is checked if not a number if ! [[ $c =~ $re ]] then calculate #This is a function defined Above else q=$[$q+1] arr[q]=$c fi else break fi cnt=$[$cnt+1] done echo -e "Result of Expression is ${arr[0]}\n"
code/data_structures/src/stack/postfix_to_prefix/README.md
# Stack Description --- Stacks are an abstract data type (ADT) that function to store and manipulate data. Their order is last-in-first-out (LIFO). To implement a stack, an array or [linked list](../linked_list) can be used. A stack is similar to a [Tower of Hanoi](https://iq.opengenus.org/tower-of-hanoi/) in that the first object pushed onto the stack cannot be removed until every other object pushed on top of it has also been removed. It is also similar to a stack of plates in a cafeteria, where the bottom plate cannot be removed until all of the plates above it have been removed as well. Functions --- - Pop() --Removes an item from the stack - Push() --Adds an item to the stack - Peek() --Returns the top element of the stack - isEmpty() --Returns true if the stack is empty Time Complexity --- All the functions are O(1).
code/data_structures/src/stack/postfix_to_prefix/postfix_to_prefix.cpp
// Part of Cosmos by OpenGenus Foundation #include <bits/stdc++.h> using namespace std; bool ValidOperator(char x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } string PostfixToPrefix(string post_exp) { stack<string> s; int length = post_exp.size(); for (int i = 0; i < length; i++) { if (ValidOperator(post_exp[i])) { string op1 = s.top(); s.pop(); string op2 = s.top(); s.pop(); string temp = post_exp[i] + op2 + op1; s.push(temp); } else { s.push(string(1, post_exp[i])); } } return s.top(); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); string post_exp = "HACKT+O*BER/-COS/MOS-*"; cout << "Prefix : " << PostfixToPrefix(post_exp); return 0; }
code/data_structures/src/stack/prefix_to_postfix/README.md
# Stack Description --- Stacks are an abstract data type (ADT) that function to store and manipulate data. Their order is last-in-first-out (LIFO). To implement a stack, an array or [linked list](../linked_list) can be used. A stack is similar to a [Tower of Hanoi](https://en.wikipedia.org/wiki/Tower_of_Hanoi) in that the first object pushed onto the stack cannot be removed until every other object pushed on top of it has also been removed. It is also similar to a stack of plates in a cafeteria, where the bottom plate cannot be removed until all of the plates above it have been removed as well. Functions --- - Pop() --Removes an item from the stack - Push() --Adds an item to the stack - Peek() --Returns the top element of the stack - isEmpty() --Returns true if the stack is empty Time Complexity --- All the functions are O(1). ![visualization](https://ssodelta.files.wordpress.com/2014/10/stack.png)
code/data_structures/src/stack/prefix_to_postfix/prefix_to_postfix.py
# Converting prefix to its equivalent postfix notation. # Part of Cosmos by OpenGenus Foundation postfix = [] operator = -10 operand = -20 empty = -50 def typeof(s): if s is "(" or s is ")": return operator elif s is "+" or s is "-" or s is "*" or s is "%" or s is "/": return operator elif s is " ": return empty else: return operand prefix = input("Enter the prefix notation : ") prefix = prefix[::-1] print(prefix) for i in prefix: type = typeof(i) if type is operand: postfix.append(i) elif type is operator: op_first = postfix.pop() op_second = postfix.pop() postfix.append(op_first + op_second + i) elif type is empty: continue print("It's postfix notation is ", "".join(postfix))
code/data_structures/src/stack/reverse_array_using_stack/reverse_array_using_stack.cpp
#include<bits/stdc++.h> using namespace std; int main(){ int n; cin>>n; int arr[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } stack<int>s; for(int i=0;i<n;i++){ s.push(arr[i]); } while(!s.empty()){ cout<<s.top()<<" "; s.pop(); } cout<<endl; return 0; }
code/data_structures/src/stack/reverse_stack/README.md
# Stack Description --- Stacks are an abstract data type (ADT) that function to store and manipulate data. Their order is last-in-first-out (LIFO). To implement a stack, an array or [linked list](../linked_list) can be used. A stack is similar to a [Tower of Hanoi](https://en.wikipedia.org/wiki/Tower_of_Hanoi) in that the first object pushed onto the stack cannot be removed until every other object pushed on top of it has also been removed. It is also similar to a stack of plates in a cafeteria, where the bottom plate cannot be removed until all of the plates above it have been removed as well. Functions --- - Pop() --Removes an item from the stack - Push() --Adds an item to the stack - Peek() --Returns the top element of the stack - isEmpty() --Returns true if the stack is empty Time Complexity --- All the functions are O(1). ![visualization](https://ssodelta.files.wordpress.com/2014/10/stack.png)
code/data_structures/src/stack/reverse_stack/reverse_stack.c
// C program to reverse a stack using recursion // Part of Cosmos by OpenGenus Foundation #include<stdio.h> #include<stdlib.h> #define bool int /* structure of a stack node */ struct sNode { char data; struct sNode *next; }; /* Function Prototypes */ void push(struct sNode** top_ref, int new_data); int pop(struct sNode** top_ref); bool isEmpty(struct sNode* top); void print(struct sNode* top); void insertAtBottom(struct sNode** top_ref, int item); void reverse(struct sNode** top_ref); /* Driver program to test above functions */ int main() { struct sNode *s = NULL; push(&s, 4); push(&s, 3); push(&s, 2); push(&s, 1); printf("\n Original Stack "); print(s); reverse(&s); printf("\n Reversed Stack "); print(s); return 0; } // Below is a recursive function that inserts an element // at the bottom of a stack. void insertAtBottom(struct sNode** top_ref, int item) { if (isEmpty(*top_ref)) push(top_ref, item); else { /* Hold all items in Function Call Stack until we reach end of the stack. When the stack becomes empty, the isEmpty(*top_ref)becomes true, the above if part is executed and the item is inserted at the bottom */ int temp = pop(top_ref); insertAtBottom(top_ref, item); /* Once the item is inserted at the bottom, push all the items held in Function Call Stack */ push(top_ref, temp); } } // Below is the function that reverses the given stack using // insertAtBottom() void reverse(struct sNode** top_ref) { if (!isEmpty(*top_ref)) { /* Hold all items in Function Call Stack until we reach end of the stack */ int temp = pop(top_ref); reverse(top_ref); /* Insert all the items (held in Function Call Stack) one by one from the bottom to top. Every item is inserted at the bottom */ insertAtBottom(top_ref, temp); } } /* Driveer program to test above functions */ int main() { struct sNode *s = NULL; push(&s, 4); push(&s, 3); push(&s, 2); push(&s, 1); printf("\n Original Stack "); print(s); reverse(&s); printf("\n Reversed Stack "); print(s); return 0; } /* Function to check if the stack is empty */ bool isEmpty(struct sNode* top) { return (top == NULL)? 1 : 0; } /* Function to push an item to stack*/ void push(struct sNode** top_ref, int new_data) { /* allocate node */ struct sNode* new_node = (struct sNode*) malloc(sizeof(struct sNode)); if (new_node == NULL) { printf("Stack overflow \n"); exit(0); } /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*top_ref); /* move the head to point to the new node */ (*top_ref) = new_node; } /* Function to pop an item from stack*/ int pop(struct sNode** top_ref) { char res; struct sNode *top; /*If stack is empty then error */ if (*top_ref == NULL) { printf("Stack overflow \n"); exit(0); } else { top = *top_ref; res = top->data; *top_ref = top->next; free(top); return res; } } /* Functrion to pront a linked list */ void print(struct sNode* top) { printf("\n"); while (top != NULL) { printf(" %d ", top->data); top = top->next; } }
code/data_structures/src/stack/reverse_stack/reverse_stack.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; // Part of Cosmos by OpenGenus Foundation namespace reversed_stack { class Program { /// <summary> /// This will print all elements in stack /// Format :: [element1] [element2] ... /// </summary> /// <param name="STK">an object of Stack collection of type int is accepted</param> static void print(Stack<int> STK) { foreach(int val in STK) { Console.Write(val.ToString() + " "); } Console.WriteLine(); // printing new line } /// <summary> /// This will take a stack collection object of int type and returns the reverse of the same /// </summary> /// <param name="STK"></param> /// <returns></returns> static Stack<int> reverse(Stack<int> STK) { Stack<int> ret = new Stack<int>(); // a temp object of stack while(STK.Count > 0) // if stack has some value it will execute { ret.Push(STK.Pop()); // STK.pop() returns the top most value which we have to push in temp / reversed stack } return ret; } static void Main(string[] args) { Stack<int> stk = new Stack<int>(); // creating a object of inbuilt collection Stack // here i am pushing 5 numbers in stack for demo stk.Push(5); stk.Push(4); stk.Push(3); stk.Push(2); stk.Push(1); // printing original elements in stack Console.WriteLine("ORIGINAL STACK"); print(stk); // reversing the stack now stk = reverse(stk); // printing original elements in stack Console.WriteLine("REVERSED STACK"); print(stk); Console.ReadKey(); // It has stopped till key has not been pressed } } }
code/data_structures/src/stack/reverse_stack/reverse_stack.go
// Part of Cosmos by OpenGenus Foundation package main /* Expect output Current Stack is [], Is Stack empty ? true Try to push 30 into Stack Try to push 12 into Stack Try to push 34 into Stack Try to push 2 into Stack Try to push 17 into Stack Try to push 88 into Stack Reverse Stack 30 12 34 2 17 88 */ import "fmt" type Stack []int func (s *Stack) Push(v int) { *s = append(*s, v) } func (s *Stack) Pop() { length := len(*s) if length != 0 { (*s) = (*s)[:length-1] } } func (s *Stack) Top() int { return (*s)[len(*s)-1] } func (s *Stack) Empty() bool { if len(*s) == 0 { return true } return false } func (s *Stack) Reverse() { for i, j := 0, len(*s)-1; i < j; i, j = i+1, j-1 { (*s)[i], (*s)[j] = (*s)[j], (*s)[i] } } func main() { stack := Stack{} fmt.Printf("Current Stack is %s, Is Stack empty ? %v \n", stack, stack.Empty()) fmt.Printf("Try to push 30 into Stack\n") stack.Push(30) fmt.Printf("Try to push 12 into Stack\n") stack.Push(12) fmt.Printf("Try to push 34 into Stack\n") stack.Push(34) fmt.Printf("Try to push 2 into Stack\n") stack.Push(2) fmt.Printf("Try to push 17 into Stack\n") stack.Push(17) fmt.Printf("Try to push 88 into Stack\n") stack.Push(88) fmt.Println("Reverse Stack") stack.Reverse() for !stack.Empty() { fmt.Printf("%d ", stack.Top()) stack.Pop() } fmt.Printf("\n") }
code/data_structures/src/stack/reverse_stack/reverse_stack.java
// Part of Cosmos by OpenGenus Foundation import java.util.Stack; // Assuming that you already know how the Stack works, // if not, see here (code/data_structures/stack/stack) class reverseStack{ public static void main(String[] args){ // Examples Integer[] intArr = {1, 3, 2, 5, 4}; String[] stringArr = {"alpha", "beta", "gamma", "echo", "delta"}; Double[] doubleArr = {1.1, 3.2, 1.2, 4.3, 5.4}; Character[] charArr = {'D', 'E', 'L', 'T', 'A'}; Object[] mixArr = {1, "alpha", 2.1, 'D', true}; // Collecting all examples in single array Object[][] examples = {intArr, stringArr, doubleArr, charArr, mixArr}; // Convert each array of examples to stack // and store them in single stack Stack<Stack<Object>> stacks = new Stack<Stack<Object>>(); for(int i=examples.length-1; i>=0; i--) stacks.push(arrayToStack(examples[i])); // Print formatted output for each example while(!stacks.isEmpty()) print(stacks.pop()); // Print each example without storing it first System.out.println("\nWithout Storing:"); for(Object[] item: examples) print(arrayToStack(item)); } public static <T> void print(Stack<T> stack){ System.out.println("Original stack: "+stack); // Print stack after reverse System.out.println("Reversed stack: "+reverse(stack)+"\n"); } public static <T> Stack<T> arrayToStack(T[] arr){ // Push each item into stack Stack<T> stack = new Stack<T>(); for(T item: arr) stack.push(item); return stack; } public static <T> Stack<T> reverse(Stack<T> ori){ // Push each item from last to first item of ori into rev Stack<T> rev = new Stack<T>(); while(!ori.isEmpty()) rev.push(ori.pop()); return rev; } }
code/data_structures/src/stack/reverse_stack/reverse_stack.py
""" Part of Cosmos by OpenGenus Foundation """ # stack class class Stack: def __init__(self): self.items = [] # check if the stack is empty def isEmpty(self): return self.items == [] # push item into the stack def push(self, item): self.items.append(item) # pop item from the stack def pop(self): return self.items.pop() # get latest item in the stack def peek(self): return self.items[len(self.items) - 1] # get stack size def size(self): return len(self.items) # reverse stack function def reverse(stack): # temp list items = [] # pop items in the stack and append to the list # this will reverse items in the stack while not stack.isEmpty(): items.append(stack.pop()) # push reversed item back to the stack for item in items: stack.push(item) # return return stack if __name__ == "__main__": # init the stack inputStack = Stack() print( "Enter the item to push into the stack and press Enter (type 'rev' to reverse the stack)" ) while True: # get input item inputItem = input("input item: ") if inputItem == "rev" and inputStack.isEmpty(): # if stack is empty, return message print("The stack is empty") print("========== +++++ ===========") elif inputItem == "rev": # reverse the stack reverseStack = reverse(inputStack) print("reversed stack: ", reverseStack.items) break else: # push item into the stack inputStack.push(inputItem) print("current stack:", inputStack.items)
code/data_structures/src/stack/reverse_stack/reverse_stack.swift
/* Part of Cosmos by OpenGenus Foundation */ // Basic stack implementation public struct Stack<T> { private var elements: Array<T> init() { self.elements = [] } init(arrayLiteral elements: T...) { self.elements = elements } public var top: T? { return elements.last } public var size: Int { return elements.count } public var isEmpty: Bool { return elements.isEmpty } mutating public func push(_ element: T) { elements.append(element) } mutating public func pop() -> T? { return self.isEmpty ? nil : elements.removeLast() } } // Reverse method implementation extension Stack { public func printElements() { for x in self.elements.reversed() { print(x, terminator: " ") } print() } mutating private func insertAtEnd(_ element: T) { guard let top = self.pop() else { self.push(element) return } self.insertAtEnd(element) self.push(top) } mutating public func reverse() { guard let top = self.pop() else { return } self.reverse() self.insertAtEnd(top) } } func test() { var stack = Stack<Int>(arrayLiteral: 1, 3, 2, 5) print("Original stack:") stack.printElements() stack.reverse() print("Reversed stack:") stack.printElements() } test()
code/data_structures/src/stack/reverse_stack/reverse_stack_without_extra_space.cpp
/* * Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <stack> using namespace std; void InputElements(stack<int> &s) { //no. of elements to be inserted int size; cin >> size; while (size--) { int num; cin >> num; s.push(num); } } void InsertInStack(stack<int> &s, int x) { if (s.empty()) { s.push(x); return; } int cur = s.top(); s.pop(); InsertInStack(s, x); s.push(cur); } void ReverseStack(stack<int> &s) { if (s.empty()) return; int cur = s.top(); s.pop(); ReverseStack(s); InsertInStack(s, cur); } void PrintStack(stack<int> s) { while (!s.empty()) { cout << s.top() << " "; s.pop(); } cout << endl; } int main() { //Stack Decalared stack<int> s; //Inserting elements in to the stack InputElements(s); //Print stack PrintStack(s); //Reverse Stack without using any extra space ReverseStack(s); //Print again PrintStack(s); return 0; }
code/data_structures/src/stack/sort_stack/README.md
# Stack Description --- Stacks are an abstract data type (ADT) that function to store and manipulate data. Their order is last-in-first-out (LIFO). To implement a stack, an array or [linked list](../linked_list) can be used. A stack is similar to a [Tower of Hanoi](https://en.wikipedia.org/wiki/Tower_of_Hanoi) in that the first object pushed onto the stack cannot be removed until every other object pushed on top of it has also been removed. It is also similar to a stack of plates in a cafeteria, where the bottom plate cannot be removed until all of the plates above it have been removed as well. Functions --- - Pop() --Removes an item from the stack - Push() --Adds an item to the stack - Peek() --Returns the top element of the stack - isEmpty() --Returns true if the stack is empty Time Complexity --- All the functions are O(1). ![visualization](https://ssodelta.files.wordpress.com/2014/10/stack.png)
code/data_structures/src/stack/sort_stack/sort_stack.c
// C program to sort a stack using recursion // Part of Cosmos by OpenGenus Foundation #include <stdio.h> #include <stdlib.h> // Stack is represented using linked list struct stack { int data; struct stack *next; }; // Utility function to initialize stack void initStack(struct stack **s) { *s = NULL; } // Utility function to chcek if stack is empty int isEmpty(struct stack *s) { if (s == NULL) return 1; return 0; } // Utility function to push an item to stack void push(struct stack **s, int x) { struct stack *p = (struct stack *)malloc(sizeof(*p)); if (p == NULL) { fprintf(stderr, "Memory allocation failed.\n"); return; } p->data = x; p->next = *s; *s = p; } // Utility function to remove an item from stack int pop(struct stack **s) { int x; struct stack *temp; x = (*s)->data; temp = *s; (*s) = (*s)->next; free(temp); return x; } // Function to find top item int top(struct stack *s) { return (s->data); } // Recursive function to insert an item x in sorted way void sortedInsert(struct stack **s, int x) { // Base case: Either stack is empty or newly inserted // item is greater than top (more than all existing) if (isEmpty(*s) || x > top(*s)) { push(s, x); return; } // If top is greater, remove the top item and recur int temp = pop(s); sortedInsert(s, x); // Put back the top item removed earlier push(s, temp); } // Function to sort stack void sortStack(struct stack **s) { // If stack is not empty if (!isEmpty(*s)) { // Remove the top item int x = pop(s); // Sort remaining stack sortStack(s); // Push the top item back in sorted stack sortedInsert(s, x); } } // Utility function to print contents of stack void printStack(struct stack *s) { while (s) { printf("%d ", s->data); s = s->next; } printf("\n"); } // Driver Program int main(void) { struct stack *top; initStack(&top); push(&top, 30); push(&top, -5); push(&top, 18); push(&top, 14); push(&top, -3); printf("Stack elements before sorting:\n"); printStack(top); sortStack(&top); printf("\n\n"); printf("Stack elements after sorting:\n"); printStack(top); return 0; }
code/data_structures/src/stack/sort_stack/sort_stack.cpp
/* Part of Cosmos by OpenGenus Foundation */ /* Sort a stack */ #include <iostream> #include <stack> using namespace std; void InputElements(stack<int> &s) //////////// Function to insert the elements in stack { //no. of elements to be inserted int size; cin >> size; while (size--) { int num; cin >> num; s.push(num); } } void PrintStack(stack<int> s) //////////// Function to print the contents of stack { while (!s.empty()) { cout << s.top() << " "; s.pop(); } cout << endl; } void SortedInsert(stack<int> &s, int num) ////////// Function to insert a element at its right position in sorted way { if (s.empty() || s.top() > num) { s.push(num); return; } int top_element = s.top(); s.pop(); SortedInsert(s, num); s.push(top_element); } void SortStack(stack<int> &s) //////////// Function to sort the stack { if (s.empty()) return; int top_element = s.top(); s.pop(); SortStack(s); SortedInsert(s, top_element); } int main() { stack<int> s; //Inserting elements in to the stack InputElements(s); //Print stack before sorting PrintStack(s); //Sort the stack SortStack(s); //Print stack after sorting PrintStack(s); return 0; }
code/data_structures/src/stack/sort_stack/sort_stack.py
class stack: def __init__(self): self.__stack = [] pass # method to parse_stack if have already def parse_stack(self, stack): self.__stack = stack pass def push(self, value): self.__stack.append(value) pass def pop(self): self.__stack.pop() pass def get_elements(self): return self.__stack def sort(self): self.__stack = sorted(self.__stack) pass # defining stack class instance stk = stack() # pushing elements in stack stk.push(10) stk.push(2) stk.push(-1) # viewing print("Original Stack : ", stk.get_elements()) # sorting stack stk.sort() # viewing again print("Sorted Stack : ", stk.get_elements())
code/data_structures/src/stack/stack/README.md
# Stack Description --- Stacks are an abstract data type (ADT) that function to store and manipulate data. Their order is last-in-first-out (LIFO). To implement a stack, an array or [linked list](../../linked_list) can be used. A stack is similar to a [Tower of Hanoi](https://en.wikipedia.org/wiki/Tower_of_Hanoi) in that the first object pushed onto the stack cannot be removed until every other object pushed on top of it has also been removed. It is also similar to a stack of plates in a cafeteria, where the bottom plate cannot be removed until all of the plates above it have been removed as well. Functions --- - Pop() --Removes an item from the stack - Push() --Adds an item to the stack - Peek() --Returns the top element of the stack - isEmpty() --Returns true if the stack is empty Time Complexity --- All the functions are O(1). ![visualization](https://ssodelta.files.wordpress.com/2014/10/stack.png)
code/data_structures/src/stack/stack/stack.c
#include <stdio.h> #include <stdlib.h> #include <limits.h> #include <assert.h> struct Stack { int top; unsigned capacity; int* array; }; struct Stack* create_stack(unsigned capacity) { struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack)); stack->capacity = capacity; stack->top = -1; stack->array = (int*) malloc(stack->capacity * sizeof(int)); return (stack); } void delete_stack(struct Stack * stack) { /* completely deletes stack */ free(stack->array); free(stack); } int is_full(struct Stack* stack) { /* checks for overflow error */ return (stack->top == stack->capacity - 1); } int is_empty(struct Stack* stack) { /* checks for underflow error */ return (stack->top == -1); } void push(struct Stack* stack, int item) { assert(!is_full(stack)); stack->array[++stack->top] = item; } int pop(struct Stack* stack) { assert(!is_empty(stack)); return (stack->array[stack->top--]); } int main() { struct Stack* stack = create_stack(100); push(stack, 10); push(stack, 20); push(stack, 30); printf("%d popped from stack\n", pop(stack)); printf("%d popped from stack\n", pop(stack)); printf("%d popped from stack\n", pop(stack)); delete_stack(stack); return (0); }
code/data_structures/src/stack/stack/stack.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <cstdlib> #include <climits> using namespace std; template <typename T> struct Node { T n; Node* next; }; template <class T> class Stack { private: Node<T>* top; public: Stack(); ~Stack(); void push(T); T pop(); void display(); }; template <class T> Stack<T>::Stack() { top = nullptr; } template <class T> Stack<T>::~Stack() { if (top) { Node<T>* ptr = top; while (ptr) { Node<T>* tmp = ptr; ptr = ptr->next; delete tmp; } } } template <class T> void Stack<T>::push(T n) { Node<T>* ptr = new Node<T>; ptr->n = n; ptr->next = top; top = ptr; } template <class T> T Stack<T>::pop() { if (top == nullptr) return INT_MIN; Node<T>* ptr = top; T n = ptr->n; top = top->next; delete ptr; return n; } template <class T> void Stack<T>::display() { Node<T>* ptr = top; while (ptr != nullptr) { cout << ptr->n << "-> "; ptr = ptr->next; } cout << "NULL" << endl; } int main() { Stack<int> S; int n, choice; while (choice != 4) { cout << "1.Push" << endl << "2.Pop" << endl << "3.Display" << endl << "4.Exit" << endl; cin >> choice; switch (choice) { case 1: cout << "Enter the element to be entered. "; cin >> n; S.push(n); break; case 2: S.pop(); break; case 3: S.display(); break; default: break; } } return 0; }
code/data_structures/src/stack/stack/stack.cs
/** * Stack implementation using a singly-linked link. * Part of the OpenGenus/cosmos project. (https://github.com/OpenGenus/cosmos) * * A stack is a first-in first-out (FIFO) data structure. * Elements are manipulated by adding and removing elements of the top of the stack. */ using System; namespace Cosmos_Data_Structures { public class Stack<T> { //Node is a element that holds the data of the current element plus a reference to the next element. //Used to implement the singly-linked list. private class Node { public T data; public Node next; public Node(T data, Node next) { this.data = data; this.next = next; } } private Node top; public int Size { get; private set; } public Stack() { top = null; Size = 0; } //Add element to the top of the stack. public void Push(T element) { var newNode = new Node(element, top); top = newNode; Size++; } //Gets element at the top of the stack. //Throws an exception if the stack is empty. public T Peek() { if(IsEmpty()) { throw new InvalidOperationException("Cannot peek on an empty stack!"); } return top.data; } //Removes and returns the element at the top of the stack. //Throws an exception if the stack is empty. public T Pop() { if(IsEmpty()) { throw new InvalidOperationException("Cannot pop on an empty stack!"); } var oldTop = top; top = top.next; Size--; return oldTop.data; } //Returns true if stack contains no elements, false otherwise. public bool IsEmpty() { return top == null; } //Returns a string representation of the stack. public override string ToString() { Node tmp = top; string result = "Stack([Top] "; while(tmp != null) { result += tmp.data; tmp = tmp.next; if(tmp != null) { result += " -> "; } } result += ")"; return result; } } //Stack testing methods/class. public class StackTest { static void Main(string[] args) { Console.Write("Creating stack..."); var intStack = new Stack<int>(); for (int i = 0; i < 10; i++) { intStack.Push(i); } Console.WriteLine("done"); Console.WriteLine(intStack.ToString()); Console.WriteLine("Size of stack: " + intStack.Size); Console.WriteLine("Topmost element is " + intStack.Peek() + ".\n"); Console.Write("Removing elements..."); for (int i = 0; i < 3; i++) { intStack.Pop(); } Console.WriteLine("done"); Console.WriteLine(intStack.ToString()); Console.WriteLine("Size of stack: " + intStack.Size); Console.WriteLine("Topmost element is " + intStack.Peek() + ".\n"); Console.WriteLine("Press any key to continue."); Console.ReadKey(); } } }
code/data_structures/src/stack/stack/stack.erl
% Part of Cosmos by OpenGenus Foundation % Pattern matching % H -> head % T -> tail -module(stack). -export([new/0, push/2, pop/1, empty/1, peek/1]). new() -> []. push(H, T) -> [H, T]. pop([H, T]) -> {H, T}. empty([]) -> true; empty(_) -> false. peek([H, _]) -> H.
code/data_structures/src/stack/stack/stack.ex
# Part of Cosmos by OpenGenus Foundation # Pattern matching # new_element = head # items = tail defmodule Stack do def new, do: [] def push(new_element, items), do: [new_element | items] def pop([element | items]), do: {element, items} def empty?([]), do: true def empty?(_), do: false def peek([head | _]), do: head end
code/data_structures/src/stack/stack/stack.go
// Part of Cosmos by OpenGenus Foundation package main import "fmt" type Stack []int func (s *Stack) Push(v int) Stack { return append(*s, v) } func (s *Stack) Pop() Stack { length := len(*s) if length != 0 { return (*s)[:length-1] } return *s } func (s *Stack) Top() int { return (*s)[len(*s)-1] } func (s *Stack) Empty() bool { if len(*s) == 0 { return true } return false } func main() { stack := Stack{} fmt.Printf("Current Stack is %s, Is Stack empty ? %v \n", stack, stack.Empty()) fmt.Printf("Try to push 30 into Stack\n") stack = stack.Push(30) fmt.Printf("Current Stack is %v, top value is %v\n", stack, stack.Top()) fmt.Printf("Try to push 12 into Stack\n") stack = stack.Push(12) fmt.Printf("Try to push 34 into Stack\n") stack = stack.Push(34) fmt.Printf("Current Stack is %v, top value is %v\n", stack, stack.Top()) fmt.Printf("Current Stack is %v, Is Stack empty ? %v \n", stack, stack.Empty()) stack = stack.Pop() fmt.Printf("Current Stack is %v, top value is %v\n", stack, stack.Top()) stack = stack.Pop() stack = stack.Pop() fmt.Printf("Current Stack is %v, Is Stack empty ? %v\n", stack, stack.Empty()) }
code/data_structures/src/stack/stack/stack.java
/* Part of Cosmos by OpenGenus Foundation */ import java.util.ArrayList; class Stack<T>{ private int maxSize; private ArrayList<T> stackArray; private int top; public Stack(int size){ maxSize = size; stackArray = new ArrayList<>(); top = -1; } public void push(T value){ if(!isFull()){ //Checks for a full stack top++; if(stackArray.size() <= top) stackArray.add(top, value); else stackArray.set(top, value); //stackArray[top] = value; }else{ System.out.println("The stack is full, can't insert value"); } } public T pop(){ if(!isEmpty()){ //Checks for an empty stack return stackArray.get(top--); }else{ throw new IndexOutOfBoundsException(); } } public T peek(){ if(!isEmpty()){ //Checks for an empty stack return stackArray.get(top); }else{ throw new IndexOutOfBoundsException(); } } public boolean isEmpty(){ return(top == -1); } public boolean isFull(){ return(top+1 == maxSize); } public void makeEmpty(){ //Doesn't delete elements in the array but if you call top = -1; //push method after calling makeEmpty it will overwrite previous values } } public class Stacks{ /** * Main method * * @param args Command line arguments */ public static void main(String args[]){ Stack<Integer> myStack = new Stack<>(4); //Declare a stack of maximum size 4 //Populate the stack myStack.push(5); myStack.push(8); myStack.push(2); myStack.push(9); System.out.println("*********************Stack Array Implementation*********************"); System.out.println(myStack.isEmpty()); //will print false System.out.println(myStack.isFull()); //will print true System.out.println(myStack.peek()); //will print 9 System.out.println(myStack.pop()); //will print 9 System.out.println(myStack.peek()); // will print 2 } }
code/data_structures/src/stack/stack/stack.js
/* Part of Cosmos by OpenGenus Foundation */ /* Stack!! * A stack is exactly what it sounds like. An element gets added to the top of * the stack and only the element on the top may be removed. This is an example * of an array implementation of a Stack. So an element can only be added/removed * from the end of the array. */ // Functions: push, pop, peek, view, length //Creates a stack var Stack = function() { //The top of the Stack this.top = 0; //The array representation of the stack this.stack = {}; //Adds a value onto the end of the stack this.push = function(value) { this.stack[this.top] = value; this.top++; }; //Removes and returns the value at the end of the stack this.pop = function() { if (this.top === 0) { return "Stack is Empty"; } this.top--; var result = this.stack[this.top]; delete this.stack[this.top]; return result; }; //Returns the size of the stack this.size = function() { return this.top; }; //Returns the value at the end of the stack this.peek = function() { return this.stack[this.top - 1]; }; //To see all the elements in the stack this.view = function() { for (var i = 0; i < this.top; i++) console.log(this.stack[i]); }; }; //Implementation var myStack = new Stack(); myStack.push(1); myStack.push(5); myStack.push(76); myStack.push(69); myStack.push(32); myStack.push(54); console.log(myStack.size()); console.log(myStack.peek()); console.log(myStack.pop()); console.log(myStack.peek()); console.log(myStack.pop()); console.log(myStack.peek()); myStack.push(55); console.log(myStack.peek()); myStack.view();
code/data_structures/src/stack/stack/stack.php
<?php /** * Stack implementation * Part of Cosmos by OpenGenus Foundation * Note: To run this script, you need PHP >= 7.1 * * @author Lucas Soares Candalo <[email protected]> */ class Stack { /** * @var array */ private $elements = []; /** * Removes an item from the stack * * @return void */ public function pop(): void { if (!$this->isEmpty()) { array_pop($this->elements); } } /** * Adds an item to the stack * * @param int $element * @return void */ public function push(int $element): void { array_push($this->elements, $element); } /** * Gets the top element of the stack * * @return int */ public function peek(): int { return end($this->elements); } /** * Checks if the stack is empty * * @return bool true if is empty, false otherwise */ public function isEmpty(): bool { return empty($this->elements); } } class StackPrinter { /** * Print stack elements * * @param Stack $stack * @return void */ public function print(Stack $stack): void { $stackClone = clone $stack; echo "Stack elements:\n\n"; while(!$stackClone->isEmpty()) { echo $stackClone->peek()."\n"; $stackClone->pop(); } echo "\n\n"; } } $stack = new Stack(); $stackPrinter = new StackPrinter(); // Add a few elements to the stack $stack->push(10); $stack->push(20); $stack->push(30); // Print stack elements $stackPrinter->print($stack); // Remove top element from the stack $stack->pop(); // Print stack elements again $stackPrinter->print($stack); // Remove top element from the stack $stack->pop(); // Print stack elements again $stackPrinter->print($stack);
code/data_structures/src/stack/stack/stack.py
# Author: Alex Day # Purpose: Stack implementation with array in python # Date: October 2 2017 # Part of Cosmos by OpenGenus Foundation class Stack: # Quasi-Constructor def __init__(self): # Object data members self.stack_arr = [] # Just an array # When the client requests a push simply add the data to the list def push(self, data): self.stack_arr.append(data) def is_empty(self): return len(self.stack_arr) == 0 # When the client requests a pop just run the pop function on the array def pop(self): assert len(self.stack_arr) > 0, "The stack is empty!" return self.stack_arr.pop() # When the client requests a peek just return the top value def peek(self): assert len(self.stack_arr) > 0, "The stack is empty!" return self.stack_arr[-1] def main(): stk = Stack() stk.push(1) stk.push(2) print(stk.peek()) print(stk.pop()) print(stk.pop()) if __name__ == "__main__": main()
code/data_structures/src/stack/stack/stack.rb
# Part of Cosmos by OpenGenus Foundation class Stack attr_accessor :items def initialize @items = [] end def push(element) @items.push(element) end def pop @items.pop end def empty? @items.empty? end def peek @items.last end end
code/data_structures/src/stack/stack/stack.rs
pub struct Stack<T> { elements: Vec<T> } impl<T> Stack<T> { pub fn new() -> Stack<T> { Stack { elements: Vec::new() } } pub fn push(&mut self, elem: T) { self.elements.push(elem); } pub fn pop(&mut self) -> T { let last = self.elements.len() - 1; self.elements.remove(last) } pub fn peek(&mut self) -> &T { let last = self.elements.len() - 1; &self.elements[last] } pub fn peek_mut(&mut self) -> &mut T { let last = self.elements.len() - 1; &mut self.elements[last] } pub fn len(&self) -> usize { self.elements.len() } pub fn is_empty(&self) -> bool { self.elements.is_empty() } } fn main() { let mut stack = Stack::<i32>::new(); stack.push(1); stack.push(2); println!("{}", stack.pop()); stack.push(-5); println!("{}", stack.peek()); }
code/data_structures/src/stack/stack/stack.swift
/* Part of Cosmos by OpenGenus Foundation */ public struct Stack<T> { private var elements: Array<T> init() { self.elements = [] } init(arrayLiteral elements: T...) { self.elements = elements } public var top: T? { return elements.last } public var size: Int { return elements.count } public var isEmpty: Bool { return elements.isEmpty } mutating public func push(_ element: T) { elements.append(element) } mutating public func pop() -> T? { return self.isEmpty ? nil : elements.removeLast() } }
code/data_structures/src/stack/stack/stack_in_dart.dart
class StackNode<T> { T data; StackNode<T>? below; StackNode(this.data); } class Stack<T> { StackNode<T>? top; int size; Stack() : top = null, size = 0; bool get isEmpty => top == null; T pop() { if (isEmpty) throw InvalidIndexError(); var output = top!; top = top?.below; size--; return output.data; } T? peek() => top?.data; void push(T data) { var newNode = StackNode(data); if (isEmpty) { top = newNode; } else { newNode.below = top; top = newNode; } size++; } } class InvalidIndexError extends Error { @override String toString() => 'Invalid Index for this operation'; } mixin BinaryHeapIndex { int parentOf(int idx) => idx >= 0 ? ((idx - 1) / 2).truncate() : throw InvalidIndexError(); int leftOf(int idx) => 2 * idx + 1; int rightOf(int idx) => 2 * idx + 2; } typedef Comparer<T> = bool Function(T parent, T child); abstract class HeapBase<T> { bool get isEmpty; int get length; void insert(T item); void insertMany(List<T> items); void heapify(int rootIndex); T pop(); T peek(); }
code/data_structures/src/stack/stack/stack_using_array.py
stack=[] def push(item): stack.append(item) def pop(): if isEmpty(stack): return("STACK UNDERFLOW") else: itempopped=stack[-1] stack.pop display() return int(itempopped) def isEmpty(stack): return stack==[] def display(): print(stack) while True: choice=int(input("1.Push\n2.Pop\n3.Isempty\n4.Exit\n")) if choice==1: element=int(input("Enter the element to be inserted: ")) push(element) if choice==2: print("Item deleted is %s"%pop()) if choice==3: print(isEmpty(stack)) if choice==4: break
code/data_structures/src/stack/stack/stack_using_linked_list.py
class node: def __init__(self,value): self.data=value self.next=None class stack: def __init__(self,value): self.ptr=None def display(self): temp=self.ptr while temp: print (temp.data,end='->') temp=temp.next print('NULL') def insertnode(self,data): if self.ptr==None: self.ptr=node(data) else: newnode=node(data) newnode.next=self.ptr self.ptr=newnode def deletenode(self): if self.ptr==None: print("Stack is empty") return else: print("Item deleted is %s"%self.ptr.data) self.ptr=self.ptr.next def isEmpty(self): return self.ptr==None top=stack() while True: choice=int(input("1.Push\n2.Pop\n3.Isempty\n4.Exit\n")) if choice==1: element=int(input("Enter the element to be inserted: ")) top.insertnode(element) top.display() if choice==2: top.deletenode() top.display() if choice==3: print(top.isEmpty()) if choice==4: break
code/data_structures/src/stack/stack_using_queue/stack_using_queue.cpp
/** * @brief Stack Data Structure Using the Queue Data Structure * @details * Using 2 Queues inside the Stack class, we can easily implement Stack * data structure with heavy computation in push function. * * Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <queue> #include <cassert> using namespace std; class Stack { private: queue<int> main_q; // stores the current state of the stack queue<int> auxiliary_q; // used to carry out intermediate operations to implement stack int current_size = 0; // stores the current size of the stack public: int top(); void push(int val); void pop(); int size(); }; /** * Returns the top most element of the stack * @returns top element of the queue */ int Stack :: top() { return main_q.front(); } /** * @brief Inserts an element to the top of the stack. * @param val the element that will be inserted into the stack * @returns void */ void Stack :: push(int val) { auxiliary_q.push(val); while(!main_q.empty()) { auxiliary_q.push(main_q.front()); main_q.pop(); } swap(main_q, auxiliary_q); current_size++; } /** * @brief Removes the topmost element from the stack * @returns void */ void Stack :: pop() { if(main_q.empty()) { return; } main_q.pop(); current_size--; } /** * @brief Utility function to return the current size of the stack * @returns current size of stack */ int Stack :: size() { return current_size; } int main() { Stack s; s.push(1); // insert an element into the stack s.push(2); // insert an element into the stack s.push(3); // insert an element into the stack assert(s.size()==3); // size should be 3 assert(s.top()==3); // topmost element in the stack should be 3 s.pop(); // remove the topmost element from the stack assert(s.top()==2); // topmost element in the stack should now be 2 s.pop(); // remove the topmost element from the stack assert(s.top()==1); s.push(5); // insert an element into the stack assert(s.top()==5); // topmost element in the stack should now be 5 s.pop(); // remove the topmost element from the stack assert(s.top()==1); // topmost element in the stack should now be 1 assert(s.size()==1); // size should be 1 return 0; }
code/data_structures/src/stack/stack_using_queue/stack_using_queue.py
## Part of Cosmos by OpenGenus Foundation class Stack: def __init__(self): self.main_q = [] self.auxiliary_q = [] self.current_size = 0 def top(self): return self.main_q[0] def push(self, val) -> None: self.auxiliary_q.append(val) while len(self.main_q) > 0: self.auxiliary_q.append(self.main_q.pop(0)) self.main_q, self.auxiliary_q = self.auxiliary_q, self.main_q self.current_size+=1 def pop(self): if len(self.main_q) == 0: return self.main_q.pop(0) self.current_size-=1 def size(self) -> int: return self.current_size if __name__=='__main__': s = Stack() s.push(1) # insert an element into the stack s.push(2) # insert an element into the stack s.push(3) # insert an element into the stack assert(s.size()==3) # size should be 3 assert(s.top()==3) # topmost element in the stack should be 3 s.pop() # remove the topmost element from the stack assert(s.top()==2) # topmost element in the stack should now be 2 s.pop() # remove the topmost element from the stack assert(s.top()==1) s.push(5) # insert an element into the stack assert(s.top()==5) # topmost element in the stack should now be 5 s.pop() # remove the topmost element from the stack assert(s.top()==1) # topmost element in the stack should now be 1 assert(s.size()==1) # size should be 1
code/data_structures/src/tree/b_tree/b_tree/b_tree.cpp
// C++ implemntation of search() and traverse() methods #include <iostream> using namespace std; // A BTree node class BTreeNode { int *keys; // An array of keys int t; // Minimum degree (defines the range for number of keys) BTreeNode **C; // An array of child pointers int n; // Current number of keys bool leaf; // Is true when node is leaf. Otherwise false public: BTreeNode(int _t, bool _leaf); // Constructor // A function to traverse all nodes in a subtree rooted with this node void traverse(); // A function to search a key in subtree rooted with this node. BTreeNode *search(int k); // returns NULL if k is not present. // A utility function to insert a new key in this node // The assumption is, the node must be non-full when this // function is called void insertNonFull(int k); // A utility function to split the child y of this node // Note that y must be full when this function is called void splitChild(int i, BTreeNode *y); // Make BTree friend of this so that we can access private members of this // class in BTree functions friend class BTree; }; // A BTree class BTree { BTreeNode *root; // Pointer to root node int t; // Minimum degree public: // Constructor (Initializes tree as empty) BTree(int _t) { root = NULL; t = _t; } // function to traverse the tree void traverse() { if (root != NULL) root->traverse(); } // function to search a key in this tree BTreeNode* search(int k) { return (root == NULL) ? NULL : root->search(k); } void insert(int); }; // Constructor for BTreeNode class BTreeNode::BTreeNode(int _t, bool _leaf) { // Copy the given minimum degree and leaf property t = _t; leaf = _leaf; // Allocate memory for maximum number of possible keys // and child pointers keys = new int[2 * t - 1]; C = new BTreeNode *[2 * t]; // Initialize the number of keys as 0 n = 0; } // Function to traverse all nodes in a subtree rooted with this node void BTreeNode::traverse() { // There are n keys and n+1 children, travers through n keys // and first n children int i; for (i = 0; i < n; i++) { // If this is not leaf, then before printing key[i], // traverse the subtree rooted with child C[i]. if (leaf == false) C[i]->traverse(); cout << " " << keys[i]; } // Print the subtree rooted with last child if (leaf == false) C[i]->traverse(); } // Function to search key k in subtree rooted with this node BTreeNode *BTreeNode::search(int k) { // Find the first key greater than or equal to k int i = 0; while (i < n && k > keys[i]) i++; // If the found key is equal to k, return this node if (keys[i] == k) return this; // If key is not found here and this is a leaf node if (leaf == true) return NULL; // Go to the appropriate child return C[i]->search(k); } void BTree::insert(int k) { // If tree is empty if (root == NULL) { // Allocate memory for root root = new BTreeNode(t, true); root->keys[0] = k; // Insert key root->n = 1; // Update number of keys in root } else // If tree is not empty { // If root is full, then tree grows in height if (root->n == 2 * t - 1) { // Allocate memory for new root BTreeNode *s = new BTreeNode(t, false); // Make old root as child of new root s->C[0] = root; // Split the old root and move 1 key to the new root s->splitChild(0, root); // New root has two children now. Decide which of the // two children is going to have new key int i = 0; if (s->keys[0] < k) i++; s->C[i]->insertNonFull(k); // Change root root = s; } else // If root is not full, call insertNonFull for root root->insertNonFull(k); } } // A utility function to insert a new key in this node // The assumption is, the node must be non-full when this // function is called void BTreeNode::insertNonFull(int k) { // Initialize index as index of rightmost element int i = n - 1; // If this is a leaf node if (leaf == true) { // The following loop does two things // a) Finds the location of new key to be inserted // b) Moves all greater keys to one place ahead while (i >= 0 && keys[i] > k) { keys[i + 1] = keys[i]; i--; } // Insert the new key at found location keys[i + 1] = k; n = n + 1; } else // If this node is not leaf { // Find the child which is going to have the new key while (i >= 0 && keys[i] > k) i--; // See if the found child is full if (C[i + 1]->n == 2 * t - 1) { // If the child is full, then split it splitChild(i + 1, C[i + 1]); // After split, the middle key of C[i] goes up and // C[i] is splitted into two. See which of the two // is going to have the new key if (keys[i + 1] < k) i++; } C[i + 1]->insertNonFull(k); } } // A utility function to split the child y of this node // Note that y must be full when this function is called void BTreeNode::splitChild(int i, BTreeNode *y) { // Create a new node which is going to store (t-1) keys // of y BTreeNode *z = new BTreeNode(y->t, y->leaf); z->n = t - 1; // Copy the last (t-1) keys of y to z for (int j = 0; j < t - 1; j++) z->keys[j] = y->keys[j + t]; // Copy the last t children of y to z if (y->leaf == false) for (int j = 0; j < t; j++) z->C[j] = y->C[j + t]; // Reduce the number of keys in y y->n = t - 1; // Since this node is going to have a new child, // create space of new child for (int j = n; j >= i + 1; j--) C[j + 1] = C[j]; // Link the new child to this node C[i + 1] = z; // A key of y will move to this node. Find location of // new key and move all greater keys one space ahead for (int j = n - 1; j >= i; j--) keys[j + 1] = keys[j]; // Copy the middle key of y to this node keys[i] = y->keys[t - 1]; // Increment count of keys in this node n = n + 1; } // Driver program to test above functions int main() { BTree t(3); // A B-Tree with minimum degree 3 t.insert(10); t.insert(20); t.insert(5); t.insert(6); cout << "Traversal of the constucted tree is "; t.traverse(); int k = 6; (t.search(k) != NULL) ? cout << "\nPresent" : cout << "\nNot Present"; k = 15; (t.search(k) != NULL) ? cout << "\nPresent" : cout << "\nNot Present"; return 0; }
code/data_structures/src/tree/b_tree/b_tree/b_tree.py
class BTreeNode(object): """A B-Tree Node. attributes ===================== leaf : boolean, determines whether this node is a leaf. keys : list, a list of keys internal to this node c : list, a list of children of this node """ def __init__(self, leaf=False): self.leaf = leaf self.keys = [] self.c = [] def __str__(self): if self.leaf: return "Leaf BTreeNode with {0} keys\n\tK:{1}\n\tC:{2}\n".format( len(self.keys), self.keys, self.c ) else: return "Internal BTreeNode with {0} keys, {1} children\n\tK:{2}\n\n".format( len(self.keys), len(self.c), self.keys, self.c ) class BTree(object): def __init__(self, t): self.root = BTreeNode(leaf=True) self.t = t def search(self, k, x=None): """Search the B-Tree for the key k. args ===================== k : Key to search for x : (optional) Node at which to begin search. Can be None, in which case the entire tree is searched. """ if isinstance(x, BTreeNode): i = 0 while i < len(x.keys) and k > x.keys[i]: # look for index of k i += 1 if i < len(x.keys) and k == x.keys[i]: # found exact match return (x, i) elif x.leaf: # no match in keys, and is leaf ==> no match exists return None else: # search children return self.search(k, x.c[i]) else: # no node provided, search root of tree return self.search(k, self.root) def insert(self, k): r = self.root if len(r.keys) == (2 * self.t) - 1: # keys are full, so we must split s = BTreeNode() self.root = s s.c.insert(0, r) # former root is now 0th child of new root s self._split_child(s, 0) self._insert_nonfull(s, k) else: self._insert_nonfull(r, k) def _insert_nonfull(self, x, k): i = len(x.keys) - 1 if x.leaf: # insert a key x.keys.append(0) while i >= 0 and k < x.keys[i]: x.keys[i + 1] = x.keys[i] i -= 1 x.keys[i + 1] = k else: # insert a child while i >= 0 and k < x.keys[i]: i -= 1 i += 1 if len(x.c[i].keys) == (2 * self.t) - 1: self._split_child(x, i) if k > x.keys[i]: i += 1 self._insert_nonfull(x.c[i], k) def _split_child(self, x, i): t = self.t y = x.c[i] z = BTreeNode(leaf=y.leaf) # slide all children of x to the right and insert z at i+1. x.c.insert(i + 1, z) x.keys.insert(i, y.keys[t - 1]) # keys of z are t to 2t - 1, # y is then 0 to t-2 z.keys = y.keys[t : (2 * t - 1)] y.keys = y.keys[0 : (t - 1)] # children of z are t to 2t els of y.c if not y.leaf: z.c = y.c[t : (2 * t)] y.c = y.c[0 : (t - 1)] def __str__(self): r = self.root return r.__str__() + "\n".join([child.__str__() for child in r.c])
code/data_structures/src/tree/b_tree/b_tree/b_tree.swift
// Part of Cosmos by OpenGenus Foundation class BTreeNode<Key: Comparable, Value> { unowned var owner: BTree<Key, Value> fileprivate var keys = [Key]() fileprivate var values = [Value]() var children: [BTreeNode]? var isLeaf: Bool { return children == nil } var numberOfKeys: Int { return keys.count } init(owner: BTree<Key, Value>) { self.owner = owner } convenience init(owner: BTree<Key, Value>, keys: [Key], values: [Value], children: [BTreeNode]? = nil) { self.init(owner: owner) self.keys += keys self.values += values self.children = children } } extension BTreeNode { func value(for key: Key) -> Value? { var index = keys.startIndex while (index + 1) < keys.endIndex && keys[index] < key { index = (index + 1) } if key == keys[index] { return values[index] } else if key < keys[index] { return children?[index].value(for: key) } else { return children?[(index + 1)].value(for: key) } } } extension BTreeNode { func traverseKeysInOrder(_ process: (Key) -> Void) { for i in 0..<numberOfKeys { children?[i].traverseKeysInOrder(process) process(keys[i]) } children?.last?.traverseKeysInOrder(process) } } extension BTreeNode { func insert(_ value: Value, for key: Key) { var index = keys.startIndex while index < keys.endIndex && keys[index] < key { index = (index + 1) } if index < keys.endIndex && keys[index] == key { values[index] = value return } if isLeaf { keys.insert(key, at: index) values.insert(value, at: index) owner.numberOfKeys += 1 } else { children![index].insert(value, for: key) if children![index].numberOfKeys > owner.order * 2 { split(child: children![index], atIndex: index) } } } private func split(child: BTreeNode, atIndex index: Int) { let middleIndex = child.numberOfKeys / 2 keys.insert(child.keys[middleIndex], at: index) values.insert(child.values[middleIndex], at: index) child.keys.remove(at: middleIndex) child.values.remove(at: middleIndex) let rightSibling = BTreeNode( owner: owner, keys: Array(child.keys[child.keys.indices.suffix(from: middleIndex)]), values: Array(child.values[child.values.indices.suffix(from: middleIndex)]) ) child.keys.removeSubrange(child.keys.indices.suffix(from: middleIndex)) child.values.removeSubrange(child.values.indices.suffix(from: middleIndex)) children!.insert(rightSibling, at: (index + 1)) if child.children != nil { rightSibling.children = Array( child.children![child.children!.indices.suffix(from: (middleIndex + 1))] ) child.children!.removeSubrange(child.children!.indices.suffix(from: (middleIndex + 1))) } } } private enum BTreeNodePosition { case left case right } extension BTreeNode { private var inorderPredecessor: BTreeNode { if isLeaf { return self } else { return children!.last!.inorderPredecessor } } func remove(_ key: Key) { var index = keys.startIndex while (index + 1) < keys.endIndex && keys[index] < key { index = (index + 1) } if keys[index] == key { if isLeaf { keys.remove(at: index) values.remove(at: index) owner.numberOfKeys -= 1 } else { let predecessor = children![index].inorderPredecessor keys[index] = predecessor.keys.last! values[index] = predecessor.values.last! children![index].remove(keys[index]) if children![index].numberOfKeys < owner.order { fix(childWithTooFewKeys: children![index], atIndex: index) } } } else if key < keys[index] { if let leftChild = children?[index] { leftChild.remove(key) if leftChild.numberOfKeys < owner.order { fix(childWithTooFewKeys: leftChild, atIndex: index) } } else { print("The key:\(key) is not in the tree.") } } else { if let rightChild = children?[(index + 1)] { rightChild.remove(key) if rightChild.numberOfKeys < owner.order { fix(childWithTooFewKeys: rightChild, atIndex: (index + 1)) } } else { print("The key:\(key) is not in the tree") } } } private func fix(childWithTooFewKeys child: BTreeNode, atIndex index: Int) { if (index - 1) >= 0 && children![(index - 1)].numberOfKeys > owner.order { move(keyAtIndex: (index - 1), to: child, from: children![(index - 1)], at: .left) } else if (index + 1) < children!.count && children![(index + 1)].numberOfKeys > owner.order { move(keyAtIndex: index, to: child, from: children![(index + 1)], at: .right) } else if (index - 1) >= 0 { merge(child: child, atIndex: index, to: .left) } else { merge(child: child, atIndex: index, to: .right) } } private func move(keyAtIndex index: Int, to targetNode: BTreeNode, from node: BTreeNode, at position: BTreeNodePosition) { switch position { case .left: targetNode.keys.insert(keys[index], at: targetNode.keys.startIndex) targetNode.values.insert(values[index], at: targetNode.values.startIndex) keys[index] = node.keys.last! values[index] = node.values.last! node.keys.removeLast() node.values.removeLast() if !targetNode.isLeaf { targetNode.children!.insert(node.children!.last!, at: targetNode.children!.startIndex) node.children!.removeLast() } case .right: targetNode.keys.insert(keys[index], at: targetNode.keys.endIndex) targetNode.values.insert(values[index], at: targetNode.values.endIndex) keys[index] = node.keys.first! values[index] = node.values.first! node.keys.removeFirst() node.values.removeFirst() if !targetNode.isLeaf { targetNode.children!.insert(node.children!.first!, at: targetNode.children!.endIndex) node.children!.removeFirst() } } } private func merge(child: BTreeNode, atIndex index: Int, to position: BTreeNodePosition) { switch position { case .left: children![(index - 1)].keys = children![(index - 1)].keys + [keys[(index - 1)]] + child.keys children![(index - 1)].values = children![(index - 1)].values + [values[(index - 1)]] + child.values keys.remove(at: (index - 1)) values.remove(at: (index - 1)) if !child.isLeaf { children![(index - 1)].children = children![(index - 1)].children! + child.children! } case .right: children![(index + 1)].keys = child.keys + [keys[index]] + children![(index + 1)].keys children![(index + 1)].values = child.values + [values[index]] + children![(index + 1)].values keys.remove(at: index) values.remove(at: index) if !child.isLeaf { children![(index + 1)].children = child.children! + children![(index + 1)].children! } } children!.remove(at: index) } } extension BTreeNode { var inorderArrayFromKeys: [Key] { var array = [Key] () for i in 0..<numberOfKeys { if let returnedArray = children?[i].inorderArrayFromKeys { array += returnedArray } array += [keys[i]] } if let returnedArray = children?.last?.inorderArrayFromKeys { array += returnedArray } return array } } public class BTree<Key: Comparable, Value> { public let order: Int var rootNode: BTreeNode<Key, Value>! fileprivate(set) public var numberOfKeys = 0 public init?(order: Int) { guard order > 0 else { print("Order has to be greater than 0.") return nil } self.order = order rootNode = BTreeNode<Key, Value>(owner: self) } } extension BTree { public func traverseKeysInOrder(_ process: (Key) -> Void) { rootNode.traverseKeysInOrder(process) } } private func splitRoot() { let middleIndexOfOldRoot = rootNode.numberOfKeys / 2 let newRoot = BTreeNode<Key, Value>( owner: self, keys: [rootNode.keys[middleIndexOfOldRoot]], values: [rootNode.values[middleIndexOfOldRoot]], children: [rootNode] ) rootNode.keys.remove(at: middleIndexOfOldRoot) rootNode.values.remove(at: middleIndexOfOldRoot) let newRightChild = BTreeNode<Key, Value>( owner: self, keys: Array(rootNode.keys[rootNode.keys.indices.suffix(from: middleIndexOfOldRoot)]), values: Array(rootNode.values[rootNode.values.indices.suffix(from: middleIndexOfOldRoot)]) ) rootNode.keys.removeSubrange(rootNode.keys.indices.suffix(from: middleIndexOfOldRoot)) rootNode.values.removeSubrange(rootNode.values.indices.suffix(from: middleIndexOfOldRoot)) if rootNode.children != nil { newRightChild.children = Array( rootNode.children![rootNode.children!.indices.suffix(from: (middleIndexOfOldRoot + 1))] ) rootNode.children!.removeSubrange( rootNode.children!.indices.suffix(from: (middleIndexOfOldRoot + 1)) ) } newRoot.children!.append(newRightChild) rootNode = newRoot } } // MARK: BTree extension: Removal extension BTree { /** * Removes `key` and the value associated with it from the tree. * * - Parameters: * - key: the key to remove */ public func remove(_ key: Key) { guard rootNode.numberOfKeys > 0 else { return } rootNode.remove(key) if rootNode.numberOfKeys == 0 && !rootNode.isLeaf { rootNode = rootNode.children!.first! } } } extension BTree { public var inorderArrayFromKeys: [Key] { return rootNode.inorderArrayFromKeys } } extension BTree: CustomStringConvertible { public var description: String { return rootNode.description } }
code/data_structures/src/tree/b_tree/b_tree/b_tree_c/README.md
# B tree ### C implementation Change the macro MIN_DEGREE in btree.h to define the minimum degree of the btree.
code/data_structures/src/tree/b_tree/b_tree/b_tree_c/btree.c
// Part of Cosmos by OpenGenus Foundation // Author : ABDOUS Kamel // Implementation of a disk-stored B-Tree #include "btree.h" #include <stdlib.h> /* * Binary search in a node. * Returns 1 in success and stores the position in i. * Otherwise returns 0 and i contains the position where the value is supposed to be. */ int bnode_search(TVal v, int* i, BNode* n) { int bi = 0, bs = n->nb_n - 1; while(bi <= bs) { *i = (bi + bs) / 2; if(n->vals[*i] == v) return 1; else if(n->vals[*i] < v) bi = *i + 1; else bs = *i - 1; } *i = bi; return 0; } /* * Inserts v in n and keeps the values sorted. * rc is the right child of the value (-1 if it hasn't). */ void bnode_ins(TVal v, int rc, BNode* n) { if(n->nb_n == MAX_N) return ; int i = n->nb_n - 1; while(i >= 0 && n->vals[i] > v) { n->vals[i + 1] = n->vals[i]; n->childs[i + 2] = n->childs[i + 1]; i--; } n->vals[i + 1] = v; n->childs[i + 2] = rc; n->nb_n++; } /* * Deletes v from the node n. */ void bnode_del(TVal v, BNode* n) { int i = 0; if(!bnode_search(v, &i, n)) return; n->nb_n--; while(i < n->nb_n) { n->vals[i] = n->vals[i + 1]; n->childs[i + 1] = n->childs[i + 2]; } } void inordre(BTree* f, int i) { BNode buff; ReadBlock(f, &buff, i); int j; for(j = 0; j < buff.nb_n; ++j) { if(buff.childs[j] != -1) inordre(f, buff.childs[j]); printf("%d ", buff.vals[j]); } if(buff.childs[j] != -1) inordre(f, buff.childs[j]); } /* * Returns 1 and the block that contains c in buff, and its num in i, and the position of c in j. * If the value doesn't exist, returns 0. */ int btree_find(BTree* bt, TVal c, int* i, int* j, BNode* buff) { *i = BTreeRoot(bt); *j = 0; initStack(&bt->stack); while(*i != -1) { ReadBlock(bt, buff, *i); if(bnode_search(c, j, buff)) return 1; pushStack(&bt->stack, *i, buff); *i = buff->childs[*j]; } if(bt->stack.head != -1) popStack(&bt->stack, i, buff); return 0; } void btree_ins(BTree* bt, TVal c) { int i, j, k, median; BNode buff, brother; if(btree_find(bt, c, &i, &j, &buff)) return; bt->fileHeader.nbVals++; if(i == -1) { bt->fileHeader.root = AllocBlock(bt); buff.vals[0] = c; buff.nb_n = 1; buff.childs[0] = buff.childs[1] = -1; WriteBlock(bt, &buff, BTreeRoot(bt)); } int stop = 0, rc = -1; while(!stop) { if(buff.nb_n != MAX_N) { stop = 1; bnode_ins(c, rc, &buff); WriteBlock(bt, &buff, i); } else { for(j = MAX_N / 2 + 1, k = 0; j < MAX_N; ++j, ++k) { brother.vals[k] = buff.vals[j]; brother.childs[k] = buff.childs[j]; } brother.childs[k] = buff.childs[j]; brother.nb_n = buff.nb_n = MAX_N / 2; median = buff.vals[MAX_N / 2]; if(c < median) bnode_ins(c, rc, &buff); else bnode_ins(c, rc, &brother); rc = AllocBlock(bt); WriteBlock(bt, &buff, i); WriteBlock(bt, &brother, rc); if(bt->stack.head != -1) { c = median; popStack(&bt->stack, &i, &buff); } else { bt->fileHeader.height++; bt->fileHeader.root = AllocBlock(bt); buff.childs[0] = i; buff.childs[1] = rc; buff.vals[0] = median; buff.nb_n = 1; WriteBlock(bt, &buff, BTreeRoot(bt)); stop = 1; } } } } // ------------------------------------------------------------------------ // void initStack(BStack* stack) { stack->head = -1; } void pushStack(BStack* stack, int adr, BNode* n) { if(stack->head == MAX_S - 1) return; stack->head++; stack->adrs[stack->head] = adr; stack->nodes[stack->head] = *n; } void popStack(BStack* stack, int* adr, BNode* n) { if(stack->head == -1) return; *adr = stack->adrs[stack->head]; *n = stack->nodes[stack->head]; stack->head--; } void getStackHead(BStack* stack, int* adr, BNode* n) { if(stack->head == -1) return; *adr = stack->adrs[stack->head]; *n = stack->nodes[stack->head]; } /* * Function to call to open a disk-stored b-tree. * if mode = 'N' : it creates a new btree. * else (you can put 'O') : it reads the btree stored in fpath. */ BTree* OpenBTree(char* fpath, char mode) { BTree* bt = malloc(sizeof(BTree)); if(mode == 'N') { bt->treeFile = fopen(fpath, "wb+"); if(bt->treeFile == NULL) { free(bt); return NULL; } bt->fileHeader.root = bt->fileHeader.freeBlocksHead = -1; bt->fileHeader.nbNodes = bt->fileHeader.nbVals = bt->fileHeader.height = 0; fwrite(&(bt->fileHeader), sizeof(FileHeader), 1, bt->treeFile); } else { bt->treeFile = fopen(fpath, "rb+"); if(bt->treeFile == NULL) { free(bt); return NULL; } fread(&(bt->fileHeader), sizeof(FileHeader), 1, bt->treeFile); } return bt; } /* * Close the btree. * Writes the tree header in the file. */ void CloseBTree(BTree* f) { fseek(f->treeFile, 0, SEEK_SET); fwrite(&(f->fileHeader), sizeof(FileHeader), 1, f->treeFile); fclose(f->treeFile); free(f); } void ReadBlock(BTree* f, BNode* buff, int i) { fseek(f->treeFile, sizeof(FileHeader) + i * sizeof(BNode), SEEK_SET); fread(buff, sizeof(BNode), 1, f->treeFile); } void WriteBlock(BTree* f, BNode* buff, int i) { fseek(f->treeFile, sizeof(FileHeader) + i * sizeof(BNode), SEEK_SET); fwrite(buff, sizeof(BNode), 1, f->treeFile); } /* * If the freeBlocks list isn't empty, takes the head of the list as a new block. * Else, it allocs a new block on the disk. */ int AllocBlock(BTree* f) { int i = f->fileHeader.freeBlocksHead; BNode buf; if(i != -1) { ReadBlock(f, &buf, i); f->fileHeader.freeBlocksHead = buf.childs[0]; } else { i = f->fileHeader.nbNodes++; buf.nb_n = 0; WriteBlock(f, &buf, i); } return i; } /* * This function also adds the block to the freeBlocks list. */ void FreeBlock(BTree* f, BNode* buff, int i) { buff->childs[0] = f->fileHeader.freeBlocksHead; f->fileHeader.freeBlocksHead = i; WriteBlock(f, buff, i); } int BTreeRoot(BTree* f) { return f->fileHeader.root; }
code/data_structures/src/tree/b_tree/b_tree/b_tree_c/btree.h
// Part of Cosmos by OpenGenus Foundation // Author : ABDOUS Kamel // Implementation of a disk-stored B-Tree #ifndef BTREE_H_INCLUDED #define BTREE_H_INCLUDED #include <stdio.h> #define MIN_DEGREE 2 #define MAX_N ((MIN_DEGREE * 2) - 1) /* Max nb of values stored in a node */ #define MAX_C (MIN_DEGREE * 2) /* Max nb of childs of a node */ #define MAX_S 20 /* Size of the stack */ typedef int TVal; /* This struct contains information about the disk-stored b-tree */ typedef struct { int root; /* Block num of the root */ int nbNodes; int nbVals; int height; /* In the file that contains the b-tree, there's a list of the blocks that are no longer used by the tree. This field contains the block num of the head of this list. If this list is not empty, we use a block of the list when we need a new block instead of allocating a new one. */ int freeBlocksHead; } FileHeader; typedef struct { TVal vals[MAX_N]; int childs[MAX_C]; int nb_n; // Nb values stored in the node } BNode; /* That a static stack */ typedef struct { int head; int adrs[MAX_S]; BNode nodes[MAX_S]; } BStack; /* That's the struct to use to manipulate a b-tree */ typedef struct { FILE* treeFile; FileHeader fileHeader; BStack stack; } BTree; /* * Binary search in a node. * Returns 1 in success and stores the position in i. * Otherwise returns 0 and i contains the position where the value is supposed to be. */ int bnode_search(TVal v, int* i, BNode* n); /* * Inserts v in n and keeps the values sorted. * rc is the right child of the value (-1 if it hasn't). */ void bnode_ins(TVal v, int rc, BNode* n); /* * Deletes v from the node n. */ void bnode_del(TVal v, BNode* n); void inordre(BTree* f, int i); /* * Returns 1 and the block that contains c in buff, and its num in i, and the position of c in j. * If the value doesn't exist, returns 0. */ int btree_find(BTree* bt, TVal c, int* i, int* j, BNode* buff); void btree_ins(BTree* bt, TVal c); // ------------------------------------------------------------------- // void initStack(BStack* stack); void pushStack(BStack* stack, int adr, BNode* n); void popStack(BStack* stack, int* adr, BNode* n); void getStackHead(BStack* stack, int* adr, BNode* n); /* * Function to call to open a disk-stored b-tree. * if mode = 'N' : it creates a new btree. * else (you can put 'O') : it reads the btree stored in fpath. */ BTree* OpenBTree(char* fpath, char mode); /* * Close the btree. * Writes the tree header in the file. */ void CloseBTree(BTree* f); void ReadBlock(BTree* f, BNode* buff, int i); void WriteBlock(BTree* f, BNode* buff, int i); /* * If the freeBlocks list isn't empty, takes the head of the list as a new block. * Else, it allocs a new block on the disk. */ int AllocBlock(BTree* f); /* * This function also adds the block to the freeBlocks list. */ void FreeBlock(BTree* f, BNode* buff, int i); int BTreeRoot(BTree* f); #endif // BTREE_H_INCLUDED
code/data_structures/src/tree/b_tree/b_tree/b_tree_c/main.c
// Part of Cosmos by OpenGenus Foundation // Author : ABDOUS Kamel // Implementation of a disk-stored B-Tree #include <stdio.h> #include <stdlib.h> #include "btree.h" int main() { BTree* bt = OpenBTree("btree.bin", 'N'); btree_ins(bt, 5); btree_ins(bt, 10); btree_ins(bt, 1); btree_ins(bt, 2); btree_ins(bt, 20); btree_ins(bt, 15); inordre(bt, BTreeRoot(bt)); CloseBTree(bt); return 0; }
code/data_structures/src/tree/b_tree/two_three_tree/twothreetree.scala
sealed trait TwoThree[T] { def insert(newEl: T): TwoThree[T] def height(): Int def printSideways(indent: Int): Unit } case class OneLeaf[T](data: T)(implicit ord: Ordering[T]) extends TwoThree[T] { def insert(newEl: T): TwoThree[T] = { if (newEl == data) this else if (ord.lt(newEl, data)) TwoLeaf(newEl, data) else TwoLeaf(data, newEl) } def height(): Int = 1 def printSideways(indent: Int): Unit = { println("\t" * indent + data) } } case class TwoLeaf[T](dataLeft: T, dataRight: T)(implicit ord: Ordering[T]) extends TwoThree[T] { def insert(newEl: T): TwoThree[T] = { if (newEl == dataLeft || newEl == dataRight) this else if (ord.lt(newEl, dataLeft)) TwoNode(dataLeft, OneLeaf(newEl), OneLeaf(dataRight)) else if (ord.lt(newEl, dataRight)) TwoNode(newEl, OneLeaf(dataLeft), OneLeaf(dataRight)) else TwoNode(dataRight, OneLeaf(dataLeft), OneLeaf(newEl)) } def height(): Int = 1 def printSideways(indent: Int): Unit = { println("\t" * indent + dataRight) println("\t" * indent + dataLeft) } } case class TwoNode[T](data: T, left: TwoThree[T], right: TwoThree[T])(implicit ord: Ordering[T]) extends TwoThree[T] { def insert(newEl: T): TwoThree[T] = { if (newEl == data) { this } else if (ord.lt(newEl, data)) { left match { case _: OneLeaf[T] => copy(left = left.insert(newEl)) case TwoLeaf(leftData, rightData) => if (ord.lt(newEl, leftData)) { ThreeNode(leftData, data, OneLeaf(newEl), OneLeaf(rightData), right) } else if (ord.lt(newEl, rightData)) { ThreeNode(newEl, data, OneLeaf(leftData), OneLeaf(rightData), right) } else { ThreeNode(rightData, data, OneLeaf(leftData), OneLeaf(newEl), right) } case leftTwo: TwoNode[T] => leftTwo.insert(newEl) match { case twoNodeChild: TwoNode[T] => ThreeNode(twoNodeChild.data, data, twoNodeChild.left, twoNodeChild.right, right) case otherChild: TwoThree[T] => this.copy(left = otherChild) } case t: ThreeNode[T] => this.copy(left = t) } } else { right match { case _: OneLeaf[T] => copy(right = right.insert(newEl)) case TwoLeaf(leftData, rightData) => if (ord.gt(newEl, rightData)) { ThreeNode(data, rightData, left, OneLeaf(leftData), OneLeaf(newEl)) } else if (ord.gt(newEl, leftData)) { ThreeNode(data, newEl, left, OneLeaf(leftData), OneLeaf(rightData)) } else { ThreeNode(data, leftData, left, OneLeaf(newEl), OneLeaf(rightData)) } case rightTwo: TwoNode[T] => rightTwo.insert(newEl) match { case twoNodeChild: TwoNode[T] => ThreeNode(data, twoNodeChild.data, left, twoNodeChild.left, twoNodeChild.right) case otherChild: TwoThree[T] => this.copy(right = otherChild) } case t: ThreeNode[T] => this.copy(right = t) } } } def height(): Int = 1 + left.height() def printSideways(indent: Int): Unit = { right.printSideways(indent + 1) println("\t" * indent + data) left.printSideways(indent + 1) } } case class ThreeNode[T](dataLeft: T, dataRight: T, left: TwoThree[T], mid: TwoThree[T], right: TwoThree[T])(implicit ord: Ordering[T]) extends TwoThree[T] { def insert(newEl: T): TwoThree[T] = { if (newEl == dataLeft || newEl == dataRight) { this } else if (ord.lt(newEl, dataLeft)) { left.insert(newEl) match { case t: TwoNode[T] => TwoNode(dataLeft, t, TwoNode(dataRight, mid, right)) case t: TwoThree[T] => this.copy(left = t) } } else if (ord.lt(newEl, dataRight)) { mid.insert(newEl) match { case TwoNode(d, l, r) => TwoNode(d, TwoNode(dataLeft, left, l), TwoNode(dataRight, r, right)) case t: TwoThree[T] => this.copy(mid = t) } } else { right.insert(newEl) match { case t: TwoNode[T] => TwoNode(dataRight, TwoNode(dataLeft, left, mid), t) case t: TwoThree[T] => this.copy(right = t) } } } def height(): Int = 1 + left.height() def printSideways(indent: Int): Unit = { right.printSideways(indent + 1) println("\t" * indent + dataRight) mid.printSideways(indent + 1) println("\t" * indent + dataLeft) left.printSideways(indent + 1) } } object Main { def main(args: Array[String]): Unit = { TwoLeaf(-3, 5).printSideways(0) OneLeaf(5).printSideways(0) OneLeaf(5).insert(-3).printSideways(0) println(OneLeaf(5).insert(-3).insert(5).insert(6)) println(OneLeaf(5).insert(-3).insert(4)) println(OneLeaf(5).insert(-3).insert(4).insert(6)) println(OneLeaf(5).insert(-3).insert(4).insert(6).insert(3)) OneLeaf(5).insert(-3).insert(4).insert(6).insert(3).insert(7).printSideways(0) } }
code/data_structures/src/tree/binary_tree/aa_tree/README.md
# Cosmos Collaborative effort by [OpenGenus](https://github.com/OpenGenus/cosmos)
code/data_structures/src/tree/binary_tree/aa_tree/aa_tree.cpp
/* * Part of Cosmos by OpenGenus Foundation * arne andersson tree synopsis * * template<typename _Derive, typename _Tp, typename _Comp = std::less<_Tp> > * struct BinaryTreeNode { * _Tp value; * std::shared_ptr<_Derive> left, right; * BinaryTreeNode(_Tp v, * std::shared_ptr<_Derive> l = nullptr, * std::shared_ptr<_Derive> r = nullptr); * }; * * template<typename _Tp, typename _Comp = std::less<_Tp> > * struct AABinaryTreeNode :public BinaryTreeNode<AABinaryTreeNode<_Tp, _Comp>, _Tp, _Comp> { * size_t level; * AABinaryTreeNode(_Tp v, * std::shared_ptr<AABinaryTreeNode> l = nullptr, * std::shared_ptr<AABinaryTreeNode> r = nullptr); * }; * * template<typename _Tp, * typename _Comp = std::less<_Tp>, * typename _NodeType = BinaryTreeNode<_Tp, _Comp> > * class BinaryTree { * public: * typedef _Tp value_type; * typedef value_type & reference; * typedef value_type const &const_reference; * typedef std::ptrdiff_t difference_type; * typedef size_t size_type; * * protected: * typedef BinaryTree<_Tp, _Comp, _NodeType> self; * typedef _NodeType node_type; * typedef std::shared_ptr<node_type> p_node_type; * * public: * BinaryTree(p_node_type r = nullptr) :root_(r), sz_(0), comp_(_Comp()), release_(true); * * p_node_type const maximum() const; * * p_node_type const minimum() const; * * size_type size() const; * * bool empty() const; * * void inOrder(std::ostream &output) const; * * void preOrder(std::ostream &output) const; * * void postOrder(std::ostream &output) const; * * protected: * p_node_type root_; * size_type sz_; * _Comp comp_; * bool release_; * p_node_type nil_; * * p_node_type get(const_reference value); * * p_node_type const maximum(p_node_type n) const; * * p_node_type const minimum(p_node_type n) const; * * void inOrder(std::ostream &output, p_node_type const n) const; * * void preOrder(std::ostream &output, p_node_type const n) const; * * void postOrder(std::ostream &output, p_node_type const n) const; * }; * * template<typename _Tp, typename _Comp = std::less<_Tp> > * class AATree :public BinaryTree<_Tp, _Comp, AABinaryTreeNode<_Tp, _Comp> > { * private: * typedef BinaryTree<_Tp, _Comp, AABinaryTreeNode<_Tp, _Comp> > base; * typedef AATree<_Tp, _Comp> self; * * public: * using typename base::size_type; * using typename base::value_type; * using typename base::reference; * using typename base::const_reference; * using typename base::difference_type; * * protected: * using typename base::p_node_type; * using typename base::node_type; * using base::root_; * using base::comp_; * using base::nil_; * using base::sz_; * * public: * AATree() :base(); * * void insert(const_reference value); * * void erase(const_reference value); * * p_node_type const find(const_reference value); * * private: * // implement by recursive * void insert(p_node_type &n, const_reference value); * * void erase(p_node_type &n, const_reference value); * * // input: T, a node representing an AA tree that needs to be rebalanced. * // output: Another node representing the rebalanced AA tree. * p_node_type skew(p_node_type n); * * // input: T, a node representing an AA tree that needs to be rebalanced. * // output: Another node representing the rebalanced AA tree * p_node_type split(p_node_type n); * * void makeNode(p_node_type &n, value_type value); * }; */ #include <algorithm> #include <functional> #include <memory> #include <stack> #include <cstddef> template<typename _Derive, typename _Tp, typename _Comp = std::less<_Tp>> struct BinaryTreeNode { _Tp value; std::shared_ptr<_Derive> left, right; BinaryTreeNode(_Tp v, std::shared_ptr<_Derive> l = nullptr, std::shared_ptr<_Derive> r = nullptr) : value(v), left(l), right(r) { }; }; template<typename _Tp, typename _Comp = std::less<_Tp>> struct AABinaryTreeNode : public BinaryTreeNode<AABinaryTreeNode<_Tp, _Comp>, _Tp, _Comp> { size_t level; AABinaryTreeNode(_Tp v, std::shared_ptr<AABinaryTreeNode> l = nullptr, std::shared_ptr<AABinaryTreeNode> r = nullptr) : BinaryTreeNode<AABinaryTreeNode<_Tp, _Comp>, _Tp, _Comp>(v, l, r), level(1) { }; }; template<typename _Tp, typename _Comp = std::less<_Tp>, typename _NodeType = BinaryTreeNode<_Tp, _Comp>> class BinaryTree { public: typedef _Tp value_type; typedef value_type & reference; typedef value_type const &const_reference; typedef std::ptrdiff_t difference_type; typedef size_t size_type; protected: typedef BinaryTree<_Tp, _Comp, _NodeType> self; typedef _NodeType node_type; typedef std::shared_ptr<node_type> p_node_type; public: BinaryTree(p_node_type r = nullptr) : root_(r), sz_(0), comp_(_Comp()), release_(true) { }; p_node_type const maximum() const { auto f = maximum(root_); if (f == nil_) return nullptr; return f; } p_node_type const minimum() const { auto f = minimum(root_); if (f == nil_) return nullptr; return f; } size_type size() const { return sz_; } bool empty() const { return sz_ == 0; } void inOrder(std::ostream &output) const { inOrder(output, root_); } void preOrder(std::ostream &output) const { preOrder(output, root_); } void postOrder(std::ostream &output) const { postOrder(output, root_); } protected: p_node_type root_; size_type sz_; _Comp comp_; bool release_; p_node_type nil_; p_node_type get(const_reference value) { p_node_type n = root_; while (n != nil_) { if (comp_(value, n->value)) n = n->left; else if (comp_(n->value, value)) n = n->right; else break; } return n; } p_node_type const maximum(p_node_type n) const { if (n != nil_) while (n->right != nil_) n = n->right; return n; } p_node_type const minimum(p_node_type n) const { if (n != nil_) while (n->left != nil_) n = n->left; return n; } void inOrder(std::ostream &output, p_node_type const n) const { if (n != nil_) { inOrder(output, n->left); output << n->value << " "; inOrder(output, n->right); } } void preOrder(std::ostream &output, p_node_type const n) const { if (n != nil_) { output << n->value << " "; preOrder(output, n->left); preOrder(output, n->right); } } void postOrder(std::ostream &output, p_node_type const n) const { if (n != nil_) { postOrder(output, n->left); output << n->value << " "; postOrder(output, n->right); } } }; template<typename _Tp, typename _Comp = std::less<_Tp>> class AATree : public BinaryTree<_Tp, _Comp, AABinaryTreeNode<_Tp, _Comp>> { private: typedef BinaryTree<_Tp, _Comp, AABinaryTreeNode<_Tp, _Comp>> base; typedef AATree<_Tp, _Comp> self; public: using typename base::size_type; using typename base::value_type; using typename base::reference; using typename base::const_reference; using typename base::difference_type; protected: using typename base::p_node_type; using typename base::node_type; using base::root_; using base::comp_; using base::nil_; using base::sz_; public: AATree() : base() { nil_ = std::make_shared<node_type>(0); nil_->left = nil_; nil_->right = nil_; nil_->level = 0; root_ = nil_; } void insert(const_reference value) { insert(root_, value); } void erase(const_reference value) { erase(root_, value); } p_node_type const find(const_reference value) { auto f = base::get(value); if (f == nil_) return nullptr; return f; } private: // implement by recursive void insert(p_node_type &n, const_reference value) { if (n == nil_) { makeNode(n, value); ++sz_; } else { if (comp_(value, n->value)) insert(n->left, value); else if (comp_(n->value, value)) insert(n->right, value); else // depend on implement n->value = value; } n = skew(n); n = split(n); } void erase(p_node_type &n, const_reference value) { if (n != nil_) { if (comp_(value, n->value)) erase(n->left, value); else if (comp_(n->value, value)) erase(n->right, value); else { if (n->left != nil_ && n->right != nil_) { p_node_type leftMax = n->left; while (leftMax->right != nil_) leftMax = leftMax->right; n->value = leftMax->value; erase(n->left, n->value); } else // 3 way, n is leaf then nullptr, otherwise n successor { p_node_type successor = n->left == nil_ ? n->right : n->left; n = successor; --sz_; } } } if (n != nil_ && (n->left->level < n->level - 1 || n->right->level < n->level - 1)) { --n->level; if (n->right->level > n->level) n->right->level = n->level; n = skew(n); if (n->right != nil_) n->right = skew(n->right); if (n->right != nil_ && n->right != nil_) n->right->right = skew(n->right->right); n = split(n); if (n->right != nil_) n->right = split(n->right); } } // input: T, a node representing an AA tree that needs to be rebalanced. // output: Another node representing the rebalanced AA tree. p_node_type skew(p_node_type n) { if (n != nil_ && n->left != nil_ && n->left->level == n->level) { p_node_type left = n->left; n->left = left->right; left->right = n; n = left; } return n; } // input: T, a node representing an AA tree that needs to be rebalanced. // output: Another node representing the rebalanced AA tree p_node_type split(p_node_type n) { if (n != nil_ && n->right != nil_ && n->right->right != nil_ && n->level == n->right->right->level) { p_node_type right = n->right; n->right = right->left; right->left = n; n = right; ++n->level; } return n; } void makeNode(p_node_type &n, value_type value) { n = std::make_shared<node_type>(value, nil_, nil_); } }; /* * // for test * // test insert/erase/size function #include <iostream> * using namespace std; * * int main() { * std::shared_ptr<AATree<int> > aat = make_shared<AATree<int> >(); * * if (!aat->empty()) * cout << "error"; * * auto f = aat->find(3); * if (f != nullptr) * cout << "error"; * * f = aat->maximum(); * if (f != nullptr) * cout << "error"; * * f = aat->minimum(); * if (f != nullptr) * cout << "error"; * * aat->insert(0); * f = aat->find(0); * if (f == nullptr) * cout << "error"; * * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->insert(1); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->insert(2); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->insert(3); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->insert(4); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->insert(5); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->insert(6); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->erase(0); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->erase(3); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->erase(1); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->insert(7); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->insert(3); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->erase(7); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->erase(3); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->insert(3); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->insert(1); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->erase(7); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * aat->erase(8); * aat->inOrder(cout); cout << "\n"; aat->preOrder(cout); cout << "\n"; * cout << aat->size() << "\n\n"; * * f = aat->maximum(); * if (f == nullptr || f->value != 6) * cout << "error"; * * f = aat->minimum(); * if (f == nullptr || f->value != 1) * cout << "error"; * * if (aat->empty()) * cout << "error"; * * return 0; * } * * * expected: * 0 * 0 * 1 * * 0 1 * 0 1 * 2 * * 0 1 2 * 1 0 2 * 3 * * 0 1 2 3 * 1 0 2 3 * 4 * * 0 1 2 3 4 * 1 0 3 2 4 * 5 * * 0 1 2 3 4 5 * 1 0 3 2 4 5 * 6 * * 0 1 2 3 4 5 6 * 3 1 0 2 5 4 6 * 7 * * 1 2 3 4 5 6 * 3 1 2 5 4 6 * 6 * * 1 2 4 5 6 * 2 1 5 4 6 * 5 * * 2 4 5 6 * 4 2 5 6 * 4 * * 2 4 5 6 7 * 4 2 6 5 7 * 5 * * 2 3 4 5 6 7 * 4 2 3 6 5 7 * 6 * * 2 3 4 5 6 * 4 2 3 5 6 * 5 * * 2 4 5 6 * 4 2 5 6 * 4 * * 2 3 4 5 6 * 4 2 3 5 6 * 5 * * 1 2 3 4 5 6 * 2 1 4 3 5 6 * 6 * * 1 2 3 4 5 6 * 2 1 4 3 5 6 * 6 * * 1 2 3 4 5 6 * 2 1 4 3 5 6 * 6 * */
code/data_structures/src/tree/binary_tree/avl_tree/avl_tree.c
#include <stdio.h> #include <stdlib.h> struct node { struct node *lcptr; int data; int height; struct node *rcptr; }; struct node *rptr = NULL; int c = 0,f = 0; int height(struct node *rptr) { if (rptr == NULL) return (-1); else return (rptr->height); } void heightUpdate(struct node *rptr) { int leftHeight = height(rptr->lcptr); int rightHeight = height(rptr->rcptr); if (leftHeight > rightHeight) rptr->height = leftHeight + 1; else rptr->height = rightHeight + 1; } int getBalance(struct node *rptr) { if (rptr == NULL) return (0); else return (height(rptr->lcptr) - height(rptr->rcptr)); } struct node * RightRotate(struct node *rptr) { struct node *jptr = rptr; struct node *kptr = rptr->lcptr; jptr->lcptr = kptr->rcptr; kptr->rcptr = jptr; heightUpdate(jptr); heightUpdate(kptr); return (kptr); } struct node * LeftRotate(struct node *rptr) { struct node *jptr = srptr; struct node *kptr = rptr->rcptr; jptr->rcptr = kptr->lcptr; kptr->lcptr = jptr; heightUpdate(jptr); heightUpdate(kptr); return (kptr); } struct node * LeftRightRotate(struct node *rptr) { struct node *jptr = rptr; struct node *kptr = rptr->lcptr; jptr->lcptr = LeftRotate(kptr); return RightRotate(jptr); } struct node * RightLeftRotate(struct node *rptr) { struct node *jptr = rptr; struct node *kptr = rptr->rcptr; jptr->rcptr = RightRotate(kptr); return LeftRotate(jptr); } struct node * insert(struct node *rptr, int x) { if (rptr == NULL) { rptr = (struct node *)malloc(sizeof(struct node)); rptr->data = x; rptr->lcptr = rptr->rcptr = NULL; rptr->height = 0; } else { if (x < rptr->data) { rptr->lcptr = insert(rptr->lcptr,x); if (getBalance(rptr) == 2 && x < (rptr->lcptr)->data) rptr = RightRotate(rptr); else if (getBalance(rptr) == 2 && x >= (rptr->lcptr)->data) rptr = LeftRightRotate(rptr); } else { rptr->rcptr = insert(rptr->rcptr,x); if (getBalance(rptr) == -2 && x < (rptr->rcptr)->data) rptr = RightLeftRotate(rptr); else if (getBalance(rptr) == -2 && x >= (rptr->rcptr)->data) rptr = LeftRotate(rptr); } heightUpdate(rptr); } return (rptr); } struct node * inorder_successor(struct node *rptr) { struct node *t = rptr->rcptr; while (t->lcptr != NULL) t = t->lcptr; return (t); } struct node * delete(struct node *rptr, int x) { if (rptr == NULL) return rptr; if (x < rptr->data) rptr->lcptr = delete(rptr->lcptr, x); else if (x > rptr->data) rptr->rcptr = delete(rptr->rcptr, x); else { if (rptr->lcptr == NULL) { struct node *temp = rptr->rcptr; free(rptr); f = 1; return (temp); } else if (rptr->rcptr == NULL) { struct node *temp = rptr->lcptr; free(rptr); f = 1; return (temp); } struct node *temp = inorder_successor(rptr); rptr->data = temp->data; rptr->rcptr = delete(rptr->rcptr, temp->data); } if (rptr == NULL) return (rptr); heightUpdate(rptr); if (getBalance(rptr) > 1 && getBalance(rptr->lcptr) >= 0) return (RightRotate(rptr)); if (getBalance(rptr) > 1 && getBalance(rptr->lcptr) < 0) return (LeftRightRotate(rptr)); if (getBalance(rptr) < -1 && getBalance(rptr->rcptr) <= 0) return (LeftRotate(rptr)); if (getBalance(rptr) < -1 && getBalance(rptr->rcptr) > 0) return (RightLeftRotate(rptr)); return (rptr); } void inorder(struct node *rptr) { if (rptr != NULL) { inorder(rptr->lcptr); printf("%d ",rptr->data); inorder(rptr->rcptr); } } void preorder(struct node *rptr) { if (rptr != NULL) { printf("%d ",rptr->data); preorder(rptr->lcptr); preorder(rptr->rcptr); } } void postorder(struct node *rptr) { if (rptr != NULL) { postorder(rptr->lcptr); postorder(rptr->rcptr); printf("%d ",rptr->data); } } void search(int x) { struct node *t = rptr; int f = 0; while (t != NULL) { if (x < t->data) t = t->lcptr; else if (x > t->data) t = t->rcptr; else { f = 1; break; } } if (f == 1) printf("%d is found in AVL\n",x); else printf("%d is not found in AVL\n",x); } void count(struct node *rptr) { if (rptr != NULL) { count(rptr->lcptr); count(rptr->rcptr); c++; } } void avlcheck(struct node *rptr) { if (rptr != NULL) { avlcheck(rptr->lcptr); avlcheck(rptr->rcptr); printf("Data: %d Balance Factor: %d\n",rptr->data,getBalance(rptr)); } } int main() { int t; while (1) { printf("1.Insert\n2.Delete\n3.Search\n4.Height\n5.Count\n6.Inorder\n7.Preorder\n8.Postorder\n9.AVL Check\n10.Exit\n"); scanf("%d",&t); switch(t) { case 1 : int x; printf("Enter integer to be inserted\n"); scanf("%d",&x); rptr = insert(rptr,x); printf("%d is successfully inserted in AVL\n",x); break; case 2 : int x; printf("Enter integer to be deleted\n"); scanf("%d",&x); f = 0; rptr = delete(rptr,x); if (f == 1) printf("%d is successfully deleted from AVL\n",x); else printf("%d is not found in AVL.Hence,cannot be deleted\n",x); break; case 3 : int x; printf("Enter integer to be searched\n"); scanf("%d",&x); search(x); break; case 4 : printf("Height of AVL: %d\n",height(rptr)); break; case 5 : c = 0; count(rptr); printf("Number of nodes present AVL:%d\n",c); break; case 6 : printf("Inorder sequence:-\n"); inorder(rptr); printf("\n"); break; case 7 : printf("Preorder sequence:-\n"); preorder(rptr); printf("\n"); break; case 8 : printf("Postorder sequence:-\n"); postorder(rptr); printf("\n"); break; case 9 : printf("Balance Factor for each node:-\n"); avlcheck(rptr); break; case 10 : return (0); } } }
code/data_structures/src/tree/binary_tree/avl_tree/avl_tree.cpp
/* * Part of Cosmos by OpenGenus Foundation * avl tree synopsis * * template<typename _Tp, typename _Comp = std::less<_Tp> > * class avl_tree { * private: * struct AVLNode { * _Tp data; * std::shared_ptr<AVLNode> left; * std::shared_ptr<AVLNode> right; * int height; * }; * * typedef _Tp value_type; * typedef AVLNode node_type; * typedef std::shared_ptr<AVLNode> p_node_type; * * public: * avl_tree() :root_(nullptr); * * // function to insert a node into the AVL tree * void insert(int data); * * // function to delete a node from the AVL tree * void erase(int data); * * // helper function to return height of a node * int getHeight(p_node_type node); * * // function to find the minimum element in the tree (lefftmost node) * p_node_type findMin(p_node_type root_); * * // function to find the maximum element in the tree (rightmost node) * p_node_type findMax(p_node_type root_); * * // preorder traversal of the AVL tree * void preOrder(std::ostream &out) const; * * // inorder traversal of the AVL tree * void inOrder(std::ostream &out) const; * * // postorder traversal of the AVL tree * void postOrder(std::ostream &out) const; * * private: * p_node_type root_; * _Comp comp_; * * // LL rotation root_ed at X * p_node_type rotateLL(p_node_type &X); * * // RR rotation root_ed at X * p_node_type rotateRR(p_node_type &X); * * // LR rotation root_ed at X * p_node_type rotateLR(p_node_type &X); * * // RL rotation root_ed at X * p_node_type rotateRL(p_node_type &X); * * // function to insert a node into the AVL tree * p_node_type insert(p_node_type root_, int data); * * // function to delete a node from the AVL tree * p_node_type erase(p_node_type root_, int data); * * // preorder traversal of the AVL tree * void preOrder(p_node_type root_, std::ostream &out) const; * * // inorder traversal of the AVL tree * void inOrder(p_node_type root_, std::ostream &out) const; * * // postorder traversal of the AVL tree * void postOrder(p_node_type root_, std::ostream &out) const; * }; */ #include <algorithm> #include <memory> #include <ostream> template<typename _Tp, typename _Comp = std::less<_Tp>> class avl_tree { private: struct AVLNode { _Tp data; std::shared_ptr<AVLNode> left; std::shared_ptr<AVLNode> right; int height; }; typedef _Tp value_type; typedef AVLNode node_type; typedef std::shared_ptr<AVLNode> p_node_type; public: avl_tree() : root_(nullptr) { ; } // function to insert a node into the AVL tree void insert(int data) { root_ = insert(root_, data); } // function to delete a node from the AVL tree void erase(int data) { root_ = erase(root_, data); } // helper function to return height of a node int getHeight(p_node_type node) { if (node) return node->height; return -1; } // function to find the minimum element in the tree (lefftmost node) p_node_type findMin(p_node_type root_) { if (root_ != nullptr) while (root_->left != nullptr) root_ = root_->left; return root_; } // function to find the maximum element in the tree (rightmost node) p_node_type findMax(p_node_type root_) { if (root_ != nullptr) while (root_->right != nullptr) root_ = root_->right; return root_; } // preorder traversal of the AVL tree void preOrder(std::ostream &out) const { preOrder(root_, out); } // inorder traversal of the AVL tree void inOrder(std::ostream &out) const { inOrder(root_, out); } // postorder traversal of the AVL tree void postOrder(std::ostream &out) const { postOrder(root_, out); } private: p_node_type root_; _Comp comp_; // LL rotation root_ed at X p_node_type rotateLL(p_node_type &X) { p_node_type W = X->left; X->left = W->right; W->right = X; X->height = std::max(getHeight(X->left), getHeight(X->right)) + 1; W->height = std::max(getHeight(W->left), getHeight(X)) + 1; return W; // new root_ } // RR rotation root_ed at X p_node_type rotateRR(p_node_type &X) { p_node_type W = X->right; X->right = W->left; W->left = X; X->height = std::max(getHeight(X->left), getHeight(X->right)) + 1; W->height = std::max(getHeight(X), getHeight(W->right)); return W; // new root_ } // LR rotation root_ed at X p_node_type rotateLR(p_node_type &X) { X->left = rotateRR(X->left); return rotateLL(X); } // RL rotation root_ed at X p_node_type rotateRL(p_node_type &X) { X->right = rotateLL(X->right); return rotateRR(X); } // function to insert a node into the AVL tree p_node_type insert(p_node_type root_, int data) { if (root_ == nullptr) { p_node_type newNode = std::make_shared<node_type>(); newNode->data = data; newNode->height = 0; newNode->left = newNode->right = nullptr; root_ = newNode; } else if (comp_(data, root_->data)) { root_->left = insert(root_->left, data); if (getHeight(root_->left) - getHeight(root_->right) == 2) { if (comp_(data, root_->left->data)) root_ = rotateLL(root_); else root_ = rotateLR(root_); } } else if (comp_(root_->data, data)) { root_->right = insert(root_->right, data); if (getHeight(root_->right) - getHeight(root_->left) == 2) { if (comp_(root_->right->data, data)) root_ = rotateRR(root_); else root_ = rotateRL(root_); } } root_->height = std::max(getHeight(root_->left), getHeight(root_->right)) + 1; return root_; } // function to delete a node from the AVL tree p_node_type erase(p_node_type root_, int data) { if (root_ == nullptr) return nullptr; else if (comp_(data, root_->data)) { root_->left = erase(root_->left, data); if (getHeight(root_->right) - getHeight(root_->left) == 2) { if (getHeight(root_->right->right) > getHeight(root_->right->left)) root_ = rotateRR(root_); else root_ = rotateRL(root_); } } else if (comp_(root_->data, data)) { root_->right = erase(root_->right, data); if (getHeight(root_->left) - getHeight(root_->right) == 2) { if (getHeight(root_->left->left) > getHeight(root_->left->right)) root_ = rotateLL(root_); else root_ = rotateLR(root_); } } else { p_node_type temp = nullptr; if (root_->left && root_->right) { temp = findMin(root_->right); root_->data = temp->data; root_->right = erase(root_->right, root_->data); if (getHeight(root_->left) - getHeight(root_->right) == 2) { if (getHeight(root_->left->left) > getHeight(root_->left->right)) root_ = rotateLL(root_); else root_ = rotateLR(root_); } } else if (root_->left) { temp = root_; root_ = root_->left; } else if (root_->right) { temp = root_; root_ = root_->right; } else return nullptr; } return root_; } // preorder traversal of the AVL tree void preOrder(p_node_type root_, std::ostream &out) const { if (root_ != nullptr) { out << (root_)->data << " "; preOrder((root_)->left, out); preOrder((root_)->right, out); } } // inorder traversal of the AVL tree void inOrder(p_node_type root_, std::ostream &out) const { if (root_ != nullptr) { inOrder((root_)->left, out); out << (root_)->data << " "; inOrder((root_)->right, out); } } // postorder traversal of the AVL tree void postOrder(p_node_type root_, std::ostream &out) const { if (root_ != nullptr) { postOrder((root_)->left, out); postOrder((root_)->right, out); out << (root_)->data << " "; } } }; /* * // for test #include <iostream> * using namespace std; * int main() { * int ch, data; * shared_ptr<avl_tree<int> > avlt = make_shared<avl_tree<int> >(); * while (1) * { * cout << "1. Insert 2. Delete 3. Preorder 4. Inorder 5. Postorder 6. Exit\n"; * cin >> ch; * switch (ch) { * case 1: cout << "Enter data\n"; * cin >> data; * avlt->insert(data); * break; * case 2: cout << "Enter data\n"; * cin >> data; * avlt->erase(data); * break; * case 3: avlt->preOrder(cout); * cout << endl; * break; * case 4: avlt->inOrder(cout); * cout << endl; * break; * case 5: avlt->postOrder(cout); * cout << endl; * break; * } * if (ch == 6) * break; * } * * return 0; * } * * // */
code/data_structures/src/tree/binary_tree/avl_tree/avl_tree.java
/*AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot be more than one for all nodes. */ class Node { int key, height; Node left, right; Node(int d) { key = d; height = 1; } } class AVLTree { Node root; // get height int height(Node N) { if (N == null) return 0; return N.height; } // get maximum of two integers int max(int a, int b) { return (a > b) ? a : b; } Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; x.right = y; y.left = T2; //Update heights y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; return x; } Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; y.left = x; x.right = T2; // Update heights x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; return y; } int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } Node insert(Node node, int key) { //Perform the normal BST rotation if (node == null) return (new Node(key)); if (key < node.key) node.left = insert(node.left, key); else if (key > node.key) node.right = insert(node.right, key); else return node; //Update height of this ancestor node node.height = 1 + max(height(node.left), height(node.right)); // Get the balance factor of this ancestor node int balance = getBalance(node); // If this node becomes unbalanced, 4 criteria if (balance > 1 && key < node.left.key) return rightRotate(node); // RR criteria if (balance < -1 && key > node.right.key) return leftRotate(node); // LR criteria if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } // RL criteria if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } return node; } // Given a non-empty BST, return the node with min. key value Node minValueNode(Node node) { Node current = node; while (current.left != null) current = current.left; return current; } Node deleteNode(Node root, int key) { //implementing bst delete if (root == null) return root; // If the key is smaller than root's key, left subtree if (key < root.key) root.left = deleteNode(root.left, key); // If the key is greater than root's key, right subtree else if (key > root.key) root.right = deleteNode(root.right, key); // if key is same as root's key, the node is deleted else { if ((root.left == null) || (root.right == null)) { Node temp = null; if (temp == root.left) temp = root.right; else temp = root.left; if (temp == null) { temp = root; root = null; } else root = temp; } else { Node temp = minValueNode(root.right); root.key = temp.key; root.right = deleteNode(root.right, temp.key); } } // If the tree had only one node then return if (root == null) return root; // update height of current node root.height = max(height(root.left), height(root.right)) + 1; // find the balance factor int balance = getBalance(root); // If this node becomes unbalanced, then there are 4 criteria // LL criteria if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); // LR criteria if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } // RR criteria if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); // RiL criteria if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } void preOrder(Node node) { if (node != null) { System.out.print(node.key + " "); preOrder(node.left); preOrder(node.right); } } public static void main(String[] args) { AVLTree tree = new AVLTree(); /* Given for instance : 10 / \ 2 11 / \ \ 1 6 12 / / \ -2 3 7 */ tree.root = tree.insert(tree.root, 10); tree.root = tree.insert(tree.root, 6); tree.root = tree.insert(tree.root, 11); tree.root = tree.insert(tree.root, 1); tree.root = tree.insert(tree.root, 7); tree.root = tree.insert(tree.root, 12); tree.root = tree.insert(tree.root, -2); tree.root = tree.insert(tree.root, 2); tree.root = tree.insert(tree.root, 3); System.out.println("Preorder traversal of "+ "constructed tree is : "); tree.preOrder(tree.root); tree.root = tree.deleteNode(tree.root, 11); System.out.println(""); System.out.println("Preorder traversal after "+ "deletion of 10 :"); tree.preOrder(tree.root); } }
code/data_structures/src/tree/binary_tree/avl_tree/avl_tree.py.py
class node: def __init__(self, num): self.value = num self.left = None self.right = None self.height = 1 class AVL: def height(self, Node): if Node is None: return 0 else: return Node.height def balance(self, Node): if Node is None: return 0 else: return self.height(Node.left) - self.height(Node.right) def rotateR(self, Node): a = Node.left b = a.right a.right = Node Node.left = b Node.height = 1 + max(self.height(Node.left), self.height(Node.right)) a.height = 1 + max(self.height(a.left), self.height(a.right)) return a def rotateL(self, Node): a = Node.right b = a.left a.left = Node Node.right = b Node.height = 1 + max(self.height(Node.left), self.height(Node.right)) a.height = 1 + max(self.height(a.left), self.height(a.right)) return a def insert(self, val, root): if root is None: return node(val) elif val <= root.value: print("\n%s Inserted as Left Child of %s" % (val, root.value)) root.left = self.insert(val, root.left) elif val > root.value: print("\n%s Inserted as Right Child of %s" % (val, root.value)) root.right = self.insert(val, root.right) root.height = 1 + max(self.height(root.left), self.height(root.right)) balance = self.balance(root) if balance > 1 and root.left.value > val: print("\nROTATE RIGHT of ", root.value) return self.rotateR(root) if balance < -1 and val > root.right.value: print("\nROTATE LEFT of ", root.value) return self.rotateL(root) if balance > 1 and val > root.left.value: print("\nROTATE LEFT of ", root.value) root.left = self.rotateL(root.left) return self.rotateR(root) if balance < -1 and val < root.right.value: print("\nROTATE RIGHT of ", root.value) root.right = self.rotateR(root.right) return self.rotateL(root) return root def inorder(self, root): if root is None: return self.inorder(root.left) print(root.value, end = '->') self.inorder(root.right) Tree = AVL() rt = None while True: choice = int(input("To Continue Insertion Enter 1 Else 0: ")) if choice == 0: break item = int(input("Enter the item to be inserted : ")) rt = Tree.insert(item, rt) Tree.inorder(rt)
code/data_structures/src/tree/binary_tree/avl_tree/avl_tree.swift
public class TreeNode<Key: Comparable, Payload> { public typealias Node = TreeNode<Key, Payload> var payload: Payload? fileprivate var key: Key internal var leftChild: Node? internal var rightChild: Node? fileprivate var height: Int fileprivate weak var parent: Node? public init(key: Key, payload: Payload?, leftChild: Node?, rightChild: Node?, parent: Node?, height: Int) { self.key = key self.payload = payload self.leftChild = leftChild self.rightChild = rightChild self.parent = parent self.height = height self.leftChild?.parent = self self.rightChild?.parent = self } public convenience init(key: Key, payload: Payload?) { self.init(key: key, payload: payload, leftChild: nil, rightChild: nil, parent: nil, height: 1) } public convenience init(key: Key) { self.init(key: key, payload: nil) } var isRoot: Bool { return parent == nil } var isLeaf: Bool { return rightChild == nil && leftChild == nil } var isLeftChild: Bool { return parent?.leftChild === self } var isRightChild: Bool { return parent?.rightChild === self } var hasLeftChild: Bool { return leftChild != nil } var hasRightChild: Bool { return rightChild != nil } var hasAnyChild: Bool { return leftChild != nil || rightChild != nil } var hasBothChildren: Bool { return leftChild != nil && rightChild != nil } } open class AVLTree<Key: Comparable, Payload> { public typealias Node = TreeNode<Key, Payload> fileprivate(set) var root: Node? fileprivate(set) var size = 0 public init() { } } extension TreeNode { public func minimum() -> TreeNode? { return leftChild?.minimum() ?? self } public func maximum() -> TreeNode? { return rightChild?.maximum() ?? self } } extension AVLTree { subscript(key: Key) -> Payload? { get { return search(input: key) } set { insert(key: key, payload: newValue) } } public func search(input: Key) -> Payload? { return search(key: input, node: root)?.payload } fileprivate func search(key: Key, node: Node?) -> Node? { if let node = node { if key == node.key { return node } else if key < node.key { return search(key: key, node: node.leftChild) } else { return search(key: key, node: node.rightChild) } } return nil } } extension AVLTree { public func insert(key: Key, payload: Payload? = nil) { if let root = root { insert(input: key, payload: payload, node: root) } else { root = Node(key: key, payload: payload) } size += 1 } private func insert(input: Key, payload: Payload?, node: Node) { if input < node.key { if let child = node.leftChild { insert(input: input, payload: payload, node: child) } else { let child = Node(key: input, payload: payload, leftChild: nil, rightChild: nil, parent: node, height: 1) node.leftChild = child balance(node: child) } } else { if let child = node.rightChild { insert(input: input, payload: payload, node: child) } else { let child = Node(key: input, payload: payload, leftChild: nil, rightChild: nil, parent: node, height: 1) node.rightChild = child balance(node: child) } } } } extension AVLTree { fileprivate func updateHeightUpwards(node: Node?) { if let node = node { let lHeight = node.leftChild?.height ?? 0 let rHeight = node.rightChild?.height ?? 0 node.height = max(lHeight, rHeight) + 1 updateHeightUpwards(node: node.parent) } } fileprivate func lrDifference(node: Node?) -> Int { let lHeight = node?.leftChild?.height ?? 0 let rHeight = node?.rightChild?.height ?? 0 return lHeight - rHeight } fileprivate func balance(node: Node?) { guard let node = node else { return } updateHeightUpwards(node: node.leftChild) updateHeightUpwards(node: node.rightChild) var nodes = [Node?](repeating: nil, count: 3) var subtrees = [Node?](repeating: nil, count: 4) let nodeParent = node.parent let lrFactor = lrDifference(node: node) if lrFactor > 1 { if lrDifference(node: node.leftChild) > 0 { nodes[0] = node nodes[2] = node.leftChild nodes[1] = nodes[2]?.leftChild subtrees[0] = nodes[1]?.leftChild subtrees[1] = nodes[1]?.rightChild subtrees[2] = nodes[2]?.rightChild subtrees[3] = nodes[0]?.rightChild } else { nodes[0] = node nodes[1] = node.leftChild nodes[2] = nodes[1]?.rightChild subtrees[0] = nodes[1]?.leftChild subtrees[1] = nodes[2]?.leftChild subtrees[2] = nodes[2]?.rightChild subtrees[3] = nodes[0]?.rightChild } } else if lrFactor < -1 { if lrDifference(node: node.rightChild) < 0 { nodes[1] = node nodes[2] = node.rightChild nodes[0] = nodes[2]?.rightChild subtrees[0] = nodes[1]?.leftChild subtrees[1] = nodes[2]?.leftChild subtrees[2] = nodes[0]?.leftChild subtrees[3] = nodes[0]?.rightChild } else { nodes[1] = node nodes[0] = node.rightChild nodes[2] = nodes[0]?.leftChild subtrees[0] = nodes[1]?.leftChild subtrees[1] = nodes[2]?.leftChild subtrees[2] = nodes[2]?.rightChild subtrees[3] = nodes[0]?.rightChild } } else { balance(node: node.parent) return } if node.isRoot { root = nodes[2] root?.parent = nil } else if node.isLeftChild { nodeParent?.leftChild = nodes[2] nodes[2]?.parent = nodeParent } else if node.isRightChild { nodeParent?.rightChild = nodes[2] nodes[2]?.parent = nodeParent } nodes[2]?.leftChild = nodes[1] nodes[1]?.parent = nodes[2] nodes[2]?.rightChild = nodes[0] nodes[0]?.parent = nodes[2] nodes[1]?.leftChild = subtrees[0] subtrees[0]?.parent = nodes[1] nodes[1]?.rightChild = subtrees[1] subtrees[1]?.parent = nodes[1] nodes[0]?.leftChild = subtrees[2] subtrees[2]?.parent = nodes[0] nodes[0]?.rightChild = subtrees[3] subtrees[3]?.parent = nodes[0] updateHeightUpwards(node: nodes[1]) updateHeightUpwards(node: nodes[0]) balance(node: nodes[2]?.parent) } } extension AVLTree { fileprivate func display(node: Node?, level: Int) { if let node = node { display(node: node.rightChild, level: level + 1) print("") if node.isRoot { print("Root -> ", terminator: "") } for _ in 0..<level { print(" ", terminator: "") } print("(\(node.key):\(node.height))", terminator: "") display(node: node.leftChild, level: level + 1) } } public func display(node: Node) { display(node: node, level: 0) print("") } } extension AVLTree { public func delete(key: Key) { if size == 1 { root = nil size -= 1 } else if let node = search(key: key, node: root) { delete(node: node) size -= 1 } } private func delete(node: Node) { if node.isLeaf { if let parent = node.parent { guard node.isLeftChild || node.isRightChild else { fatalError("Error: tree is invalid.") } if node.isLeftChild { parent.leftChild = nil } else if node.isRightChild { parent.rightChild = nil } balance(node: parent) } else { root = nil } } else { if let replacement = node.leftChild?.maximum(), replacement !== node { node.key = replacement.key node.payload = replacement.payload delete(node: replacement) } else if let replacement = node.rightChild?.minimum(), replacement !== node { node.key = replacement.key node.payload = replacement.payload delete(node: replacement) } } } }
code/data_structures/src/tree/binary_tree/binary_search_tree/BST_Operations.cpp
#include<iostream> #include<algorithm> using namespace std; class BST{ private: int data; BST *left,*right; public: //Constructors: BST(){ data=0; left=right=NULL; } BST(int val){ data=val; left=right=NULL; } //Inserting a Node into BST: BST* InsertNode(BST*,int); //Delete a Node from BST: BST* DeletNode(BST*,int); //Traversals: void InOrder(BST*); void PreOrder(BST*); void PostOrder(BST*); //Searching BST* SearchNode(BST*,int); }; BST* BST::InsertNode(BST *root,int key){ if(root==NULL){ root=new BST(key); return root; } else if(key<=root->data){ if(root->left==NULL){ root->left=new BST(key); return root; } else{ root->left=InsertNode(root->left,key); return root; } } else{ if(root->right==NULL){ root->right=new BST(key); return root; } else { root->right=InsertNode(root->right,key); return root; } } } BST* BST::DeletNode(BST *root,int key){ // Base case if (root == NULL) return root; //If root->data is greater than k then we delete the root's subtree if(root->data > key){ root->left = DeletNode(root->left, key); return root; } else if(root->data < key){ root->right = DeletNode(root->right, key); return root; } // If one of the children is empty if (root->left == NULL) { BST* temp = root->right; delete root; return temp; } else if (root->right == NULL) { BST* temp = root->left; delete root; return temp; } else { BST* Parent = root; // Find successor of the Node BST *succ = root->right; while (succ->left != NULL) { Parent = succ; succ = succ->left; } if (Parent != root) Parent->left = succ->right; else Parent->right = succ->right; // Copy Successor Data root->data = succ->data; // Delete Successor and return root delete succ; return root; } } BST* BST::SearchNode(BST *root,int key){ //Base Case if(root==NULL||root->data==key) return root; if(root->data>key){ return SearchNode(root->left,key); } return SearchNode(root->right,key); } void BST::InOrder(BST *root){ //InOrder traversal of a Binary Search Tree gives sorted order. if(root==NULL)return; InOrder(root->left); cout<<root->data<<" "; InOrder(root->right); } void BST::PreOrder(BST *root){ if(root==NULL)return; cout<<root->data<<" "; PreOrder(root->left); PreOrder(root->right); } void BST::PostOrder(BST *root){ if(root==NULL)return; PostOrder(root->left); PostOrder(root->right); cout<<root->data<<" "; } int main(){ int choice,element; BST B,*root=NULL; while(true){ cout << "------------------\n"; cout << "Operations on Binary Search Tree\n"; cout << "------------------\n"; cout << "1.Insert Element\n"; cout << "2.Delete Element\n"; cout << "3.Search Element\n"; cout << "4.Traversals\n"; cout << "5.Exit\n"; cout << "Enter your choice: "; cin >> choice; switch(choice){ case 1: cout << "Enter the element to be inserted: "; cin >> element; root=B.InsertNode(root,element); break; case 2: cout << "Enter the element to be deleted: "; cin >> element; root=B.DeletNode(root,element); break; case 3: cout << "Search Element: "; cout << "Enter the element to be Searched: "; cin >> element; if (B.SearchNode(root,element)){ cout << "Element Found \n" ; } else cout << "Element Not Found\n"; break; case 4: cout << "Displaying elements of BST: "; cout <<"\nInORder: "; B.InOrder(root); cout <<"\nPreORder: "; B.PreOrder(root); cout <<"\nPostORder: "; B.PostOrder(root); cout<<endl; break; case 5: return 1; default: cout << "Enter Correct Choice \n"; } } }
code/data_structures/src/tree/binary_tree/binary_search_tree/README.md
# Binary Search Tree Description --- Binary Search Tree is basically a binary tree which has the following properties: * The left subtree of a node contains only nodes with values **lesser** than the node’s value. * The right subtree of a node contains only nodes with value **greater** than the node’s value. * The left and right subtree each must also be a binary search tree. Operations performed on binary search tree are: 1. Insertion 2. Deletion 3. Searching Traversals of a Binary Search tree: * Inorder: `Left, Root, Right` * Preorder: `Root, Left, Right` * Postorder: `Left, Right, Root`<br> Note: In Binary Search Tree inorder traversal gives the sorted order of the elements in BST.
code/data_structures/src/tree/binary_tree/binary_tree/README.md
# Tree Description --- A tree is a data structure that is comprised of various **nodes**. Each node has at least one parent node, and can have multiple child nodes. The only node that does not have a parent node is a unique node called the **root**, or sometimes base node. If a node has no children, it can be called a **leaf**.
code/data_structures/src/tree/binary_tree/binary_tree/Subtree_sum/subtreesum_recursive.cpp
#include<iostream> using namespace std; //Binary tree structure struct node { int data; struct node* left; struct node* right; }; //for inserting a new node node *newNode(int data){ node *temp=new node; temp->data=data; temp->right=NULL; temp->left=NULL; return (temp); } //helper function //Function to return sum of subtrees and count subtrees with sum=x int countSubtreesWithSumX(node* root, int x ,int& count) { if(root==NULL) return 0; int ls= countSubtreesWithSumX(root->left,x,count); int rs= countSubtreesWithSumX(root->right,x,count); int sum=ls+rs+root->data; if(sum==x) count++; return sum; } //main function //Function to return the count of subtrees whose sum=x int countSubtreescheckroot(node* root, int x) { if(root==NULL) return 0; int count=0; //return sum of left and right subtrees respectively int ls= countSubtreesWithSumX(root->left,x,count); int rs= countSubtreesWithSumX(root->right,x,count); //checks if the root value added to sums of left and right subtrees equals x if(x==ls+rs+root->data) count++; //returns the count of subtrees with their sum=x return count; } int main() { // input of sum to check for int x; cout<<"Enter the sum to check for"<<endl; cin>>x; //sample input of the binary tree struct node* root=newNode(7); root->left=newNode(3); root->right=newNode(2); root->left->right=newNode(6); root->left->left=newNode(2); root->right->right=newNode(11); cout<<"Number of subtrees with specific sum :"<<" "<<countSubtreescheckroot(root, x)<<endl; return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/balance_binary_tree/BST.py
class BinaryTree: def __init__(self,value): self.left=None self.right=None self.value=value def insert(self,data): if self.value: if data<self.value: if self.left is None: self.left=BinaryTree(data) else: self.left.insert(data) elif data > self.value: if self.right is None: self.right=BinaryTree(data) else: self.right.insert(data) else: self.value=data def inorderprint(self): if self.left: self.left.inorderprint() print(self.value) if self.right: self.right.inorderprint() def Postorderprint(self): if self.left: self.left.Postorderprint() if self.right: self.right.Postorderprint() print(self.value) def Preorderprint(self): print(self.value) if self.left: self.left.Preorderprint() if self.right: self.right.Preorderprint() choice="s" rootvalue=int(input("Enter a value for the root: ")) root=BinaryTree(rootvalue) while(choice=="s"): e=int(input("Enter element to be inserted: ")) root.insert(e) choice=input("Do you wish to insert another element(s/n)") while(True): traversal=int(input("1.Preorder\n2.Postorder\n3.Inorder\n4.Exit\n")) if traversal==1: root.Preorderprint() if traversal==2: root.Postorderprint() if traversal==3: root.inorderprint() if traversal==4: break
code/data_structures/src/tree/binary_tree/binary_tree/balance_binary_tree/balance_bst_dsw.cpp
#include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; struct node { int key; struct node *left, *right; }; struct node *newNode(int value) { struct node *temp = new node; temp->key = value; temp->left = temp->right = NULL; return temp; } 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; } //Inorder traversal void inorder(struct node *root) { if (root) { inorder(root->left); cout << root->key << " "; inorder(root->right); } } //Preorder traversal void preorder(struct node *root) { if (root) { cout << root->key << " "; preorder(root->left); preorder(root->right); } } struct node* leftRotate(struct node * root) { struct node *right, *right_left; if ( (root == NULL) || (root->right ==NULL) ) return root; right = root->right; right_left = right->left; right->left = root; root->right = right_left; return right; } struct node* rightRotate(struct node * root){ struct node *left, *left_right; if ( (root == NULL) || (root->left == NULL) ) return root; left = root->left; left_right = left->right; left->right = root; root->left = left_right; return left; } /* Make a vine structure rooted at a dummy root and branching only towards right */ struct node* createBackbone(struct node* root) { struct node *parent, *r; r = newNode(-1); parent = r; r->right = root; // making tree skewed towards right; while (parent->right) { if (parent->right->left == NULL) parent = parent->right; else parent->right = rightRotate(parent->right); } return r; }; /* Compress the tree using series of left rotations on alternate nodes provided by the count. */ struct node* compress(struct node* root, int cnt) { struct node *temp; temp = root; while (cnt && temp) { temp->right = leftRotate(temp->right); temp = temp->right; cnt -= 1; } return root; } // To calculate height of the tree int height(struct node* root) { int left, right; if (root == NULL) return -1; left = height(root->left); right = height(root->right); left = left >= right ? left : right; return 1 + left; } struct node* balanceTree(struct node* root) { root = createBackbone(root); /* Now a dummy root is added so we get original root from root->right; */ cout << "Backbone Tree structure" << endl; cout << "Inorder traversal: "; inorder(root->right); cout << "\nPreorder traversal: "; preorder(root->right); cout << endl; // h = total number of nodes int h = height(root); int left_count, temp, l = 0; temp = h + 1; // l = log(n+1) (base 2) while (temp > 1) { temp /= 2; l += 1; } /* make n-m rotations starting from the top of backbone where m = 2^( floor(lg(n+1)))-1 */ left_count = h + 1 - (1 << l); if (left_count == 0) { left_count = (1 << (l - 1)); } root = compress(root, left_count); h -= left_count ; while (h > 1) { h /= 2; root = compress(root, h); } return root; }; int main() { /* Let us create following BST * 50 * \ * 70 * / * 60 */ struct node *root = NULL; root = insert(root, 50); insert(root, 70); insert(root, 60); // insert(root, 80); root = balanceTree(root); root = root->right; /* Back-bone structure of above BST * 50 * \ * 60 * \ * 70 */ /* Balanced BST * 60 * / \ * 50 70 */ cout << endl; cout << "Balanced Tree Structure " << endl; cout << "Inorder traversal: "; inorder(root); cout << "\nPreorder traversal: "; preorder(root); return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/convert_to_doubly_linked_list/convert_to_doubly_linked_list.cpp
/* Structure for tree and linked list * * struct Node * { * int data; * Node *left, *right; * }; * */ // root --> Root of Binary Tree // head_ref --> Pointer to head node of created doubly linked list template<typename Node> void BToDLL(Node *root, Node **head_ref) { if (!root) return; BToDLL(root->right, head_ref); root->right = *head_ref; if (*head_ref) (*head_ref)->left = root; *head_ref = root; BToDLL(root->left, head_ref); }
code/data_structures/src/tree/binary_tree/binary_tree/count_universal_subtree/count_universal_subtrees.cpp
#include <iostream> using namespace std; //binary tree structure struct node{ int data; struct node* left,*right; }; bool findUniValueST(node *root , int &count) { if(root==NULL) return true; bool right=findUniValueST(root->right,count); bool left=findUniValueST(root->left,count); //if left or right subtree is not univalued then that subtree is not univalued if(right==false||left==false) return false; //if right node exists and the value is not equal to root's value,again not univalued if(root->right && root->right->data!=root->data) return false; //same for left node also. if(root->left && root->left->data!=root->data) return false; /*if above possible conditions not satisified then its a univalued subtree. Like this we increment as and when there is a univalued subtree*/ count++; /*and return true*/ return true; } //to return count of the univalued subtrees. int countUniValueST(node *root ){ int count=0; findUniValueST(root,count); return count; } //for inserting a new node node *newNode(int data){ node *temp=new node; temp->data=data; temp->right=NULL; temp->left=NULL; return (temp); } int main() { //sample input of the binary tree struct node* root=newNode(1); root->left=newNode(3); root->right=newNode(3); root->left->right=newNode(3); root->left->left=newNode(3); cout<<"Number of univalued subtrees:"<<" "<<countUniValueST(root)<<endl; return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/diameter/README.md
# Cosmos Collaborative effort by [OpenGenus](https://github.com/OpenGenus/cosmos)
code/data_structures/src/tree/binary_tree/binary_tree/diameter/diameter.c
#include <stdio.h> #include <unistd.h> #include <stdlib.h> typedef struct node { int value; struct node *left, *right; }node; node* create_node(int ); void create_tree(int ); void cleanup_tree(node* ); int maximum(int , int ); int height_tree(node* ); int diameter_tree(node* ); 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 maximum(int left_ht, int right_ht) { return (left_ht > right_ht ? left_ht : right_ht); } int height_tree(node* tmp) { int left_ht, right_ht; if (!tmp) return 0; left_ht = height_tree(tmp->left); right_ht = height_tree(tmp->right); return 1+maximum(left_ht, right_ht); } //Prints the longest path between the leaf nodes int diameter_tree(node* tmp) { int leaf_depth, left_subtree_height, right_subtree_height, max_depth_between_left_and_right_subtree; if (!tmp) return 0; leaf_depth = height_tree(tmp->left) + height_tree(tmp->right); left_subtree_height = diameter_tree(tmp->left); right_subtree_height = diameter_tree(tmp->right); max_depth_between_left_and_right_subtree = maximum(left_subtree_height, right_subtree_height); return maximum(leaf_depth, max_depth_between_left_and_right_subtree); } void cleanup_tree(node* tmp) { if (tmp) { cleanup_tree(tmp->left); cleanup_tree(tmp->right); if (tmp->left) { free(tmp->left); tmp->left = NULL; } if (tmp->right) { free(tmp->right); tmp->right= NULL; } } if (tmp == root) { free(root); root = NULL; } } int main() { int val, num, ctr,longest_path_between_leaf_nodes; node tmp; printf("Enter number of nodes\n"); scanf("%d",&num); for (ctr = 0; ctr < num; ctr++) { printf("Enter values\n"); scanf("%d",&val); create_tree(val); } longest_path_between_leaf_nodes = diameter_tree(root); printf("diameter_tree = %d\n",longest_path_between_leaf_nodes); cleanup_tree(root); return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/diameter/diameter.cpp
/* * Part of Cosmos by OpenGenus Foundation * * diameter of tree synopsis * * template<typename _TreeNode> * size_t * diameter(_TreeNode node); * * template<typename _TreeNode> * void * diameterIterative(_TreeNode const &node, size_t &maximum); * * template<typename _TreeNode> * size_t * getDiameter(_TreeNode const &node); * * template<typename _TreeNode> * size_t * getDeep(_TreeNode const &node); * * template<typename _TreeNode> * size_t * diameterRecursive(_TreeNode node, size_t &maximum); */ #include <algorithm> #include <memory> #include <stack> #include "../node/node.cpp" template<typename _TreeNode> size_t diameter(_TreeNode node) { size_t res{}; diameterIterative(node, res); return res; } template<typename _TreeNode> void diameterIterative(_TreeNode const &node, size_t &maximum) { maximum = 0; if (node != nullptr) { std::stack<_TreeNode> diameters; diameters.push(node); // DFS while (!diameters.empty()) { while (diameters.top()->left() != nullptr) diameters.push(diameters.top()->left()); while (!diameters.empty() && (diameters.top() == nullptr || diameters.top()->right() == nullptr)) { if (diameters.top() == nullptr) // if back from right hand diameters.pop(); auto top = diameters.top(); maximum = std::max(maximum, static_cast<size_t>(getDiameter(top))); top->value(static_cast<int>(getDeep(top))); diameters.pop(); } if (!diameters.empty()) { auto right = diameters.top()->right(); diameters.push(nullptr); // prevent visit two times when return to parent diameters.push(right); } } } } template<typename _TreeNode> size_t getDiameter(_TreeNode const &node) { size_t res = 1; res += node->left() ? node->left()->value() : 0; res += node->right() ? node->right()->value() : 0; return res; } template<typename _TreeNode> size_t getDeep(_TreeNode const &node) { size_t res = 1; res += std::max(node->left() ? node->left()->value() : 0, node->right() ? node->right()->value() : 0); return res; } template<typename _TreeNode> size_t diameterRecursive(_TreeNode node, size_t &maximum) { if (node != nullptr) { size_t leftMax{}, rightMax{}; // DFS size_t leftHeight = diameterRecursive(node->left(), leftMax); size_t rightHeight = diameterRecursive(node->right(), rightMax); maximum = leftHeight + rightHeight + 1; maximum = std::max(maximum, leftMax); maximum = std::max(maximum, rightMax); return std::max(leftHeight, rightHeight) + 1; } return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/diameter/diameter.hs
data Tree = Nil | Tree `Fork` Tree deriving Show leaf :: Tree leaf = Fork Nil Nil diameter :: Tree -> Int diameter = snd . go where -- go keeps track of the diameter as well as the depth of the tree go :: Tree -> (Int, Int) go Nil = (0, 0) go (Fork t1 t2) = (ht, dt) where (h1, d1) = go t1 (h2, d2) = go t2 ht = 1 + max h1 h2 dt = maximum [(h1 + h2), d1, d2]
code/data_structures/src/tree/binary_tree/binary_tree/diameter/diameter.java
//Diameter of binary tree using java class Node { int data; Node left, right; Node(int i) { data = i; left = right = null; } } class Height { int h; } class BinaryTreeDiameter { Node root; //Function to calculate diameter int calldiameter(Node root, Height height) { Height l = new Height();//height of left sub-tree Height r = new Height();//height of right sub-tree if (root == null) { height.h = 0; return 0; } int ld = calldiameter(root.left, l);//diameter of left-subtree int rd = calldiameter(root.right, r);//diameter of right-subtree //Height of current node is max(left height,right height)+1 height.h = Math.max(l.h,r.h) + 1; return Math.max(l.h + r.h + 1, Math.max(ld, rd)); } int diameter() { Height height = new Height(); return calldiameter(root, height); } //Function to calculate height of tree static int height(Node node) { //tree is empty if (node == null) return 0; //If not empty then height = 1 + max(left height,right height) return (1 + Math.max(height(node.left), height(node.right))); } public static void main(String args[]) { //Creating a binary tree BinaryTreeDiameter t = new BinaryTreeDiameter(); t.root = new Node(1); t.root.left = new Node(3); t.root.right = new Node(2); t.root.left.left = new Node(7); t.root.left.right = new Node(6); t.root.right.left = new Node(5); t.root.right.right = new Node(4); t.root.left.left.right = new Node(10); t.root.right.left.left = new Node(9); t.root.right.left.right = new Node(8); System.out.println("The Diameter of given binary tree is : "+ t.diameter()); } } /*Input: 1 / \ 3 2 / \ / \ 7 6 5 4 \ / \ 10 9 8 */ /*Output: The Diameter of given binary tree is : 7 */
code/data_structures/src/tree/binary_tree/binary_tree/diameter/diameter.py
# Time: O(n) # Space: O(h) # Given a binary tree, you need to compute the length of the diameter of the tree. # The diameter of a binary tree is the length of the longest path between # any two nodes in a tree. This path may or may not pass through the root. # # Example: # Given a binary tree # 1 # / \ # 2 3 # / \ # 4 5 # Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. # # Note: The length of path between two nodes is represented by the number of edges between them. # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None # The function diameter_height returns the diameter and the height of the tree. # And the function find_tree_diameter uses it to just compute the diameter (by discarding the height). class Solution: def diameter_height(node): if node is None: return 0, 0 ld, lh = diameter_height(node.left) rd, rh = diameter_height(node.right) return max(lh + rh + 1, ld, rd), 1 + max(lh, rh) def find_tree_diameter(node): d, _ = diameter_height(node) return d diameter = Solution()
code/data_structures/src/tree/binary_tree/binary_tree/diameter/diameter2.c
#include <stdio.h> #include <stdlib.h> #define MAX(x, y) (((x) > (y)) ? (x) : (y)) typedef struct node{ int data; struct node *left; struct node *right; }node; node* newnode(int d){ node* temp = (node*)malloc(sizeof(node)); temp->data = d; temp->left = NULL; temp->right = NULL; } node *buildTree(){ int d; printf("\nEnter data:"); scanf("%d", &d); if(d==-1){ return NULL; } ///rec case node *n =newnode(d); n->left = buildTree(); n->right = buildTree(); return n; } int height(node *root){ if(root==NULL){ return 0; } return (MAX./(height(root->left),height(root->right))+1); } int diameter(node*root){ if(root==NULL){ return 0; } int cp1 = height(root->left) + height(root->right); int cp2 = diameter(root->left); int cp3 = diameter(root->right); return MAX(cp1,MAX(cp2,cp3)); } int main(){ node *root = NULL; root = buildTree(); printf("\nDiameter of Binary Tree: "); printf("%d", diameter(root)); return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/diameter/diameter2.cpp
/* * Data Structures : Finding Diameter of a binary tree * * Description : Diameter of tree is defined as the longest path or route between any two nodes in a tree. * This path may or may not be through the root. The below algorithm computes the height of * the tree and uses it recursivley in the calculation of diameter of the specified tree. * * A massive collaborative effort by OpenGenus Foundation */ #include <iostream> using namespace std; // get the max of two no.s int max(int a, int b) { return (a > b) ? a : b; } typedef struct node { int value; struct 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; } // compute height of the tree int getHeight(node *root) { if (root == NULL) return 0; // find the height of each subtree int lh = getHeight(root->left); int rh = getHeight(root->right); return 1 + max(lh, rh); } // compute tree diameter recursively int getDiameter(node *root) { if (root == NULL) return 0; // get height of each subtree int lh = getHeight(root->left); int rh = getHeight(root->right); // compute diameters of each subtree int ld = getDiameter(root->left); int rd = getDiameter(root->right); return max(lh + rh + 1, max(ld, rd)); } // create the tree node *createTree() { node *root = getNewNode(31); root->left = getNewNode(16); root->right = getNewNode(52); root->left->left = getNewNode(7); root->left->right = getNewNode(24); root->left->right->left = getNewNode(19); root->left->right->right = getNewNode(29); return root; } // main int main() { node *root = createTree(); cout << "\nDiameter of the tree is " << getDiameter(root); cout << endl; return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/is_balance/README.md
# Cosmos Collaborative effort by [OpenGenus](https://github.com/OpenGenus/cosmos)
code/data_structures/src/tree/binary_tree/binary_tree/is_balance/is_balance.java
class Node { int data; Node left, right; Node(int d) { data = d; left = right = null; } } class BinaryTree { Node root; /* Returns true if binary tree with root as root is height-balanced */ boolean isBalanced(Node node) { int lh; /* for height of left subtree */ int rh; /* for height of right subtree */ /* If tree is empty then return true */ if (node == null) return true; /* Get the height of left and right sub trees */ lh = height(node.left); rh = height(node.right); if (Math.abs(lh - rh) <= 1 && isBalanced(node.left) && isBalanced(node.right)) return true; /* If we reach here then tree is not height-balanced */ return false; } /* UTILITY FUNCTIONS TO TEST isBalanced() FUNCTION */ /* The function Compute the "height" of a tree. Height is the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(Node node) { /* base case tree is empty */ if (node == null) return 0; /* If tree is not empty then height = 1 + max of left height and right heights */ return 1 + Math.max(height(node.left), height(node.right)); } public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.left.left.left = new Node(8); if(tree.isBalanced(tree.root)) System.out.println("Tree is balanced"); else System.out.println("Tree is not balanced"); } }
code/data_structures/src/tree/binary_tree/binary_tree/is_binary_tree/is_binary_tree.cpp
/* A binary tree node has data, pointer to left child * and a pointer to right child * * struct Node { * int data; * Node* left, * right; * }; * */ /* Should return true if tree represented by root is BST. * For example, return value should be 1 for following tree. * 20 * / \ * 10 30 * and return value should be 0 for following tree. * 10 * / \ * 20 30 */ template<typename Node> Node *findmax(Node *root) { if (!root) return nullptr; while (root->right) root = root->right; return root; } template<typename Node> Node *findmin(Node *root) { if (!root) return nullptr; while (root->left) root = root->left; return root; } template<typename Node> bool isBST(Node* root) { if (!root) return 1; if (root->left && findmax(root->left)->data > (root->data)) return 0; if (root->right && findmin(root->right)->data < (root->data)) return 0; if (!isBST(root->left) || !isBST(root->right)) return 0; return 1; } // Another variation // Utility function //another function for the same but need to provide the min and max in the the tree beforehand template<typename Node> int isBSTUtil(Node *root, int min, int max) { if (!root) return 1; if (root->data < min || root->data > max) return 0; return isBSTUtil(root->left, min, root->data - 1) && isBSTUtil(root->right, root->data + 1, max); }
code/data_structures/src/tree/binary_tree/binary_tree/is_same/is_same.cpp
/* * Part of Cosmos by OpenGenus Foundation * * tree comparer synopsis * * template<typename _Tp, typename _Comp = std::equal_to<_Tp> > * class TreeComparer * { * public: * using NodeType = TreeNode<_Tp>; * using PNodeType = std::shared_ptr<NodeType>; * * bool isSameTree(PNodeType p, PNodeType q) const; * * private: * _Comp comp_; * }; */ #include <stack> #include <functional> #include <memory> #include "../node/node.cpp" #ifndef TREE_COMPARER #define TREE_COMPARER template<typename _Tp, typename _Comp = std::equal_to<_Tp>> class TreeComparer { public: using NodeType = TreeNode<_Tp>; using PNodeType = std::shared_ptr<NodeType>; bool isSameTree(PNodeType const &f, PNodeType const &s) const { std::stack<PNodeType> first, second; first.push(f); second.push(s); // DFS while (!first.empty() || !second.empty()) { // mining left while (first.top() != nullptr || second.top() != nullptr) { // check not same node and not same value if (first.top() == nullptr || second.top() == nullptr || !comp_(first.top()->value(), second.top()->value())) return false; first.push(first.top()->left()); second.push(second.top()->left()); } // escape if top is empty or right is empty while (!first.empty() && ((first.top() == nullptr && second.top() == nullptr) || (first.top()->right() == nullptr && second.top()->right() == nullptr))) { first.pop(); second.pop(); } if (!first.empty()) { auto first_right = first.top()->right(), second_right = second.top()->right(); first.pop(); second.pop(); first.push(first_right); second.push(second_right); } } return true; } private: _Comp comp_; }; #endif // TREE_COMPARER
code/data_structures/src/tree/binary_tree/binary_tree/make_binary_tree/README.md
# Tree Description --- A tree is a data structure that is comprised of various **nodes**. Each node has at least one parent node, and can have multiple child nodes. The only node that does not have a parent node is a unique node called the **root**, or sometimes base node. If a node has no children, it can be called a **leaf**.
code/data_structures/src/tree/binary_tree/binary_tree/make_binary_tree/from_inorder_and_postorder/make_tree_from_inorder_and_postorder.c
#include <stdlib.h> #include <stdio.h> typedef struct btree { int data; struct btree *left; struct btree *right; }btree; btree *makeTree(int *in , int *post , int start , int end , int *index) { if (start > end) return NULL; btree *nn = (btree*)malloc(sizeof(btree)); nn -> data = post[*index]; int i; for (i = start;i <= end;i++) { if (post[*index] == in[i]) break; } (*index)--; nn -> right = makeTree(in, post, i+1, end, index); nn -> left = makeTree(in, post, start, i-1, index); return nn; } void printPostOrderTree(btree *root) { if(root == NULL) return; printPostOrderTree(root -> left); printPostOrderTree(root -> right); printf("%d ",root -> data); } int main() { int post[] = {4,5,2,6,7,3,1}; int in[] = {4,2,5,1,6,3,7}; int index = 6; btree *root = makeTree (in, post, 0, 6, &index); printPostOrderTree(root); return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/make_binary_tree/from_inorder_and_postorder/make_tree_from_inorder_and_postorder.cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; template<typename T> class TreeNode { using Treetype = TreeNode<T>; public: T data; Treetype * left; Treetype * right; TreeNode(T data) : data(data), left(NULL), right(NULL) { } }; template <typename BidiIt> TreeNode<int>* buildTreeHelper(BidiIt in_first, BidiIt in_last, BidiIt post_first, BidiIt post_last); TreeNode<int>* buildTree(vector<int> &inorder, vector<int> &postorder) { return buildTreeHelper(begin(inorder), end(inorder), begin(postorder), end(postorder)); } template <typename BidiIt> TreeNode<int>* buildTreeHelper(BidiIt in_first, BidiIt in_last, BidiIt post_first, BidiIt post_last) { if (in_first == in_last) return nullptr; if (post_first == post_last) return nullptr; const auto val = *prev(post_last); TreeNode<int>* root = new TreeNode<int>(val); auto in_root_pos = find(in_first, in_last, val); auto left_size = distance(in_first, in_root_pos); auto post_left_last = next(post_first, left_size); root->left = buildTreeHelper(in_first, in_root_pos, post_first, post_left_last); root->right = buildTreeHelper(next(in_root_pos), in_last, post_left_last, prev(post_last)); return root; } void postorderPrint(TreeNode<int>* root) { if (root == NULL) return; postorderPrint(root->left); postorderPrint(root->right); cout << root->data << " "; return; } int main() { vector<int> postorder = {7, 8, 6, 4, 2, 5, 3, 1}; vector<int> inorder = {4, 7, 6, 8, 2, 1, 3, 5}; TreeNode<int>* root = buildTree(inorder, postorder); postorderPrint(root); // 7 8 6 4 2 5 3 1 return 0; } /* * // test tree is * 1 * / \ * 2 3 * / \ * 4 5 \ \ 6 \ / \ \ 7 8 */
code/data_structures/src/tree/binary_tree/binary_tree/make_binary_tree/from_inorder_and_preorder/README.md
# Cosmos Collaborative effort by [OpenGenus](https://github.com/OpenGenus/cosmos)
code/data_structures/src/tree/binary_tree/binary_tree/make_binary_tree/from_inorder_and_preorder/make_tree_from_inorder_and_preorder.c
#include<stdio.h> #include<stdlib.h> // Part of Cosmos by OpenGenus Foundation int search(int arr[], int x, int n) { for (int i = 0; i < n; i++) if (arr[i] == x) return i; return -1; } // Prints postorder traversal from given inorder and preorder traversals void printPostOrder(int in[], int pre[], int n) { // The first element in pre[] is always root, search it // in in[] to find left and right subtrees int root = search(in, pre[0], n); // If left subtree is not empty, print left subtree if (root != 0) printPostOrder(in, pre+1, root); // If right subtree is not empty, print right subtree if (root != n-1) printPostOrder(in+root+1, pre+root+1, n-root-1); printf("%d ",pre[0]); } int main() { int n; printf("Enter the no. of element in the tree"); printf("\n"); scanf("%d",&n); int in[10000]; int pre[10000]; printf("Enter elements of inorder traversal seprated by single space"); printf("\n"); for(int x=0;x< n;x++){ scanf("%d",&in[x]); } printf("Enter elements of preorder traversal by single space"); printf("\n"); for(int x=0;x< n;x++){ scanf("%d",&pre[x]); } printf("Postorder traversal "); printf("\n"); printPostOrder(in, pre, n); printf("\n"); return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/make_binary_tree/from_inorder_and_preorder/make_tree_from_inorder_and_preorder.cpp
#include <iostream> #include <cmath> #include <queue> #include <cmath> using namespace std; template<typename T> class Binarytreenode { public: T data; Binarytreenode<T> * left; Binarytreenode<T> * right; Binarytreenode(T data) { this->data = data; left = NULL; right = NULL; } }; void postorder(Binarytreenode<int>* root) { if (root == NULL) return; postorder(root->left); postorder(root->right); cout << root->data << " "; return; } Binarytreenode<int> * create(int *preorder, int*inorder, int ps, int pe, int is, int ie) { if (ps > pe || is > ie) return NULL; int rootdata = preorder[ps]; Binarytreenode<int> * root = new Binarytreenode<int>(rootdata); int k; for (int i = is; i <= ie; i++) if (inorder[i] == rootdata) { k = i; break; } root->left = create(preorder, inorder, ps + 1, ps + k - is, is, k - 1); root->right = create(preorder, inorder, ps + k - is + 1, pe, k + 1, ie); return root; } int main() { int preorder[100], inorder[100]; int size; cin >> size; for (int i = 0; i < size; i++) cin >> preorder[i]; for (int i = 0; i < size; i++) cin >> inorder[i]; Binarytreenode<int> * root = create(preorder, inorder, 0, size - 1, 0, size - 1); postorder(root); }
code/data_structures/src/tree/binary_tree/binary_tree/make_binary_tree/from_inorder_and_preorder/make_tree_from_inorder_and_preorder.java
//createdBy arora-72 //5-10-2017 // Part of Cosmos by OpenGenus Foundation public class MakeTreefromInorderAndPreorder { public static int pIndex=0; public Node makeBTree(int [] inOrder, int [] preOrder, int iStart, int iEnd ){ if(iStart>iEnd){ return null; } Node root = new Node(preOrder[pIndex]);pIndex++; if(iStart==iEnd){ return root; } int index = getInorderIndex(inOrder, iStart, iEnd, root.data); root.left = makeBTree(inOrder,preOrder,iStart, index-1); root.right = makeBTree(inOrder,preOrder,index+1, iEnd); //} return root; } public int getInorderIndex(int [] inOrder, int start, int end, int data){ for(int i=start;i<=end;i++){ if(inOrder[i]==data){ return i; } } return -1; } public void printINORDER(Node root){ if(root!=null){ printINORDER(root.left); System.out.print(" " + root.data); printINORDER(root.right); } } public static void main (String[] args) throws java.lang.Exception { int [] inOrder = {2,5,6,10,12,14,15}; int [] preOrder = {10,5,2,6,14,12,15}; MakeTreefromInorderAndPreorder i = new MakeTreefromInorderAndPreorder(); Node x = i.makeBTree(inOrder, preOrder, 0, inOrder.length-1); System.out.println("Constructed Tree : "); i.printINORDER(x); } } class Node{ int data; Node left; Node right; public Node (int data){ this.data = data; left = null; right = null; } }
code/data_structures/src/tree/binary_tree/binary_tree/make_mirror_tree/README.md
# Cosmos Collaborative effort by [OpenGenus](https://github.com/OpenGenus/cosmos)
code/data_structures/src/tree/binary_tree/binary_tree/make_mirror_tree/make_mirror_tree.c
#include <stdio.h> #include <unistd.h> #include <stdlib.h> typedef struct node { int value; struct node *left, *right; }node; node* create_node(int ); void create_tree(int ); void cleanup_tree(node* ); void mirror_image(node* ); 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; } } } } void mirror_image(node* tmp) { node* tmp1 = NULL; if (tmp) { tmp1 = tmp->left; tmp->left = tmp->right; tmp->right = tmp1; mirror_image(tmp->left); mirror_image(tmp->right); } } void print_mirror_image(node* tmp) { if (tmp) { printf("%d\n",tmp->value); print_mirror_image(tmp->left); print_mirror_image(tmp->right); } } void cleanup_tree(node* tmp) { if (tmp) { cleanup_tree(tmp->left); cleanup_tree(tmp->right); if (tmp->left) { free(tmp->left); tmp->left = NULL; } if (tmp->right) { free(tmp->right); tmp->right= NULL; } } if (tmp == root) { free(root); root = NULL; } } int main() { int val, num, ctr; node tmp; printf("Enter number of nodes\n"); scanf("%d",&num); for (ctr = 0; ctr < num; ctr++) { printf("Enter values\n"); scanf("%d",&val); create_tree(val); } mirror_image(root); print_mirror_image(root); cleanup_tree(root); return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/make_mirror_tree/make_mirror_tree.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; } // Inorder traversal of a tree void inorderTraversal(node *ptr) { if (ptr == NULL) return; else { inorderTraversal(ptr->left); cout << ptr->value << "\t"; inorderTraversal(ptr->right); } } // create mirror tree node* mirror(node* root) { node* m_root = NULL; if (!root) return NULL; m_root = getNewNode(root->value); m_root->left = mirror(root->right); m_root->right = mirror(root->left); return m_root; } // main int main() { node *root = createTree(); cout << "\n Inorder traversal before conversion "; inorderTraversal(root); node *m_root = mirror(root); cout << "\n Inorder traversal after conversion "; inorderTraversal(m_root); cout << endl; return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/make_mirror_tree/make_mirror_tree.py
# Part of Cosmos by OpenGenus Foundation class Node(object): def __init__(self, data=-1, path="", left=None, right=None): self.data = data self.path = path self.left = left self.right = right def inorder(root): if root: print(root.data, " path", root.path, end=" \n") inorder(root.left) inorder(root.right) def insertbydata(root, d, char, newd): global x if root: if root.data == d: x = root if char == "L": x.left = Node(newd, x.path + "1") # x=x.left else: x.right = Node(newd, x.path + "0") # x=x.right # print(x.data) insertbydata(root.left, d, char, newd) insertbydata(root.right, d, char, newd) def searchbypath(root, pat): global x if root: # print(root.path) if root.path == pat: x = root # print( x.data) searchbypath(root.left, pat) searchbypath(root.right, pat) if x == None: return -1 return x.data def mirror_path(st): k = "" for i in st: if i == "0": k += "1" else: k += "0" return k def searchbydata(root, d): global x if root: if root.data == d: x = root searchbydata(root.left, d) searchbydata(root.right, d) if x != None: return x return -1 head = Node(1) t = [int(i) for i in input().split()] for i in range(t[0] - 1): li = [j for j in input().split()] insertbydata(head, int(li[0]), li[2], int(li[1])) # inorder(head) for i in range(t[1]): inputd = int(input()) mirrorreflecttionofinputd = searchbypath( head, (mirror_path(searchbydata(head, inputd).path)) ) if inputd != head.data: if inputd == mirrorreflecttionofinputd: print(-1) else: print(mirrorreflecttionofinputd) else: print(head.data) """ input should be like this 10 8 1 2 R 1 3 L 2 4 R 2 5 L 3 6 R 3 7 L 5 8 R 5 9 L 7 10 R 2 5 3 6 1 10 9 4 First line of input is N and Q. Next N-1 line consists of two integers and one character first of whose is parent node , second is child node and character "L" representing Left child and "R" representing right child. Next Q lines represents qi. Output: For each qi printing the mirror node if it exists else printing -1. """
code/data_structures/src/tree/binary_tree/binary_tree/maximum_height/README.md
# Cosmos Collaborative effort by [OpenGenus](https://github.com/OpenGenus/cosmos)
code/data_structures/src/tree/binary_tree/binary_tree/maximum_height/maximum_height.cpp
#include <iostream> // #include<bits/stdc++.h> using namespace std; // Part of Cosmos by OpenGenus Foundation // #include <iostream> // using namespace std; // max function int max(int a, int b) { return (a > b) ? a : b; } struct node { int data; node* left; node* right; }; // create a new node struct node* getNode(int data) { node* newNode = new node(); newNode->data = data; newNode->left = NULL; newNode->right = NULL; return newNode; } // Inorder Traversal void inorder(struct node* root) { if (root != NULL) { inorder(root->left); cout << root->data << " "; inorder(root->right); } } //Insert new node into Binary Tree struct node* Insert(struct node* root, int data) { if (root == NULL) return getNode(data); if (data < root->data) root->left = Insert(root->left, data); else if (data > root->data) root->right = Insert(root->right, data); return root; } // compute height of the tree int getHeight(node* root) { int l; int r; if(root){ l = getHeight(root->left); r = getHeight(root->right); if(l>r){ return l+1; } else{ return r+1; } } } int main() { node* root = NULL; int a[30]; int n; cout << "\nEnter no. of nodes: "; cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; root = Insert(root, a[i]); } cout << "\n\nInorder: "; inorder(root); cout << "\n\nHeight of the tree is " << getHeight(root); return 0; }
code/data_structures/src/tree/binary_tree/binary_tree/maximum_height/maximum_height.java
import java.util.*; import java.lang.*; import java.io.*; // Java program to find height of Binary Search Tree // A binary tree node class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; } } class BinaryTreeHeight { Node root; /* Compute the "maxDepth" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int maxDepth(Node node) { if (node == null) return 0; else { /* compute the depth of each subtree */ int lDepth = maxDepth(node.left); int rDepth = maxDepth(node.right); /* use the larger one */ if (lDepth > rDepth) return (lDepth + 1); else return (rDepth + 1); } } //The main function public static void main(String[] args) { BinaryTreeHeight tree = new BinaryTreeHeight(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println("Height of tree is : " + tree.maxDepth(tree.root)); } }
code/data_structures/src/tree/binary_tree/binary_tree/maximum_height/maximum_height.py
# Part of Cosmos by OpenGenus Foundation class Node: def __init__(self, data): self.data = data self.left = None self.right = None # Compute the HEIGHT of a tree def height(node): if node is None: return 0 else: # Compute the height of each subtree lh = height(node.left) rh = height(node.right) return max(lh, rh) + 1 root = Node(11) root.left = Node(22) root.right = Node(33) root.left.left = Node(44) root.left.right = Node(66) print("Height of tree is %d" % (height(root)))
code/data_structures/src/tree/binary_tree/binary_tree/maximum_height/maximum_height2.cpp
#include <iostream> using namespace std; class node { private: int value; node* left, *right; public: node() { }; ~node() { }; node* create_node(int& val); void create_tree(int& val); int height_tree(node* tmp); void cleanup_tree(node* tmp); inline int maximum(int left_ht, int right_ht) { return left_ht > right_ht ? left_ht : right_ht; } }; static node* root = NULL; node* node::create_node(int& val) { node* tmp = new node; tmp->value = val; tmp->left = tmp->right = NULL; return tmp; } void node::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 node::height_tree(node* tmp) { if (!tmp) return 0; int left_ht = height_tree(tmp->left); int right_ht = height_tree(tmp->right); return 1 + max(left_ht, right_ht); } void node::cleanup_tree(node* tmp) { if (tmp) { cleanup_tree(tmp->left); cleanup_tree(tmp->right); if (tmp->left) delete tmp->left; if (tmp->right) delete tmp->right; } if (tmp == root) delete root; } int main() { int val, num; node tmp; cout << "Enter number of nodes" << endl; cin >> num; for (int ctr = 0; ctr < num; ctr++) { cout << "Enter values" << endl; cin >> val; tmp.create_tree(val); } int tree_ht = tmp.height_tree(root); cout << "Height of tree is " << tree_ht << endl; tmp.cleanup_tree(root); return 0; }