Tree_and_Radix_Tree
Binary tree
number of nodes in full BT: 2**(h+1)+1
number of leaf nodes: 2**h
number of leaf nodes in the full BT with n elements : (n+1)/2.
http://www.techiedelight.com/dfs-interview-questions/
http://www.geeksforgeeks.org/wp-content/uploads/Tree-Traversal.png
deep copy of binary tree
Find the longest path from a leaf to leaf (diameter of tree)
https://blogs.ncl.ac.uk/andreymokhov/walking-on-trees/ diameter of tree
http://www.cs.duke.edu/courses/spring00/cps100/assign/trees/diameter.html
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
http://www.java67.com/2016/10/how-to-print-leaf-nodes-of-binary-tree-without-recursion-in-java.html
import java.util.*;
public class BinaryTree {
//reference to root of the binary tree
public Node root;
//Node as an inner class
public class Node{
int data; //integer value that this Node holds
Node left,right; //references to left and right binary sub-trees
//constructor with the value that the node holds is passed
public Node(int data){
this.data=data;
left=null;
right=null;
}
public Node(){ //default constructor without any arguments
this.left=null;
this.right=null;
}
}
//checks if tree rooted at root1 is subtree of tree rooted at root2
public boolean isSubTree(Node root1, Node root2){
if(root1==null || root2==null)
return root1==null && root2==null;
Node n1 = searchNode(root2, root1.data);
if(n1==null)
return false;
return areEqual(root1,n1);
}
//returns the node of tree with given key
public Node searchNode(Node root,int key){
if(root==null)
return null;
if(root.data==key)
return root;
Node leftAns = searchNode(root.left,key),rightAns = searchNode(root.right,key);
return leftAns!=null ? leftAns : rightAns;
}
//checks if tree rooted at root1 and tree rooted at root2 are identical(both in terms of structure and keys)
public boolean areEqual(Node root1,Node root2){
if(root1==null || root2==null)
return root1==null && root2==null;
return root1.data==root2.data && areEqual(root1.left,root2.left) && areEqual(root1.right,root2.right);
}
}
Pseudocode for spiral level order traversal of a binary tree.
//Define two stacks S1, S2
//At each level, S1 carries the nodes to be traversed in that level S2 carries the child nodes of the nodes in S1 spiralLevelOrder(root) {
S1 = new Stack()
S2 = new Stack()
S1.push(root)
spiralLevelOrderRecursion(S1, S2, 1)
}
spiralLevelOrderRecursion(S1, S2, level) {
while(S1 not empty) {
node = S1.pop()
visit(node)
if (level is odd) {
S2.push(node.rightNode)
S2.push(node.leftNode)
} else {
S2.push(node.leftNode)
S2.push(node.rightNode)
}
}
if (S2 not empty)
spiralLevelOrderRecursion(S2, S1, level+1)
}
Sample tree : 1-(2-(4,5),3-(5,6)) format : root-(leftchild, rightchild)
Applying the pseudocode :
spiralLevelOrderRecursion([1], [], 1)
S2 - [] -> [3] -> [2, 3] visit order : 1
spiralLevelOrderRecursion([2,3], [], 2)
S2 - [] -> [4] -> [5,4] -> [6, 5, 4] -> [7, 6, 5, 4] visit order : 2, 3
spiralLevelOrderRecursion([7,6,5,4], [], 3)
visit order : 7, 6, 5, 4
Preorder traversal: print root first
1) Visit the root.
2) Traverse the left subtree.
3) Traverse the right subtree.
Serializing binary tree using preorder traversal:
http://www.leetcode.com/2010/09/serializationdeserialization-of-binary.html
http://effprog.blogspot.com/2010/08/serialize-binary-tree.html
Trie
http://nullprogram.com/blog/2016/11/13/
Radix Tree http://habrahabr.ru/post/141145/
http://stackoverflow.com/questions/9452701/ukkonens-suffix-tree-algorithm-in-plain-english
http://habrahabr.ru/blogs/algorithm/115346/
http://habrahabr.ru/post/258121/
Graph Algorithms
http://en.wikipedia.org/wiki/Tree_traversal
http://en.wikipedia.org/wiki/Graph_traversal
http://www.embeddedrelated.com/showarticle/799.php topological sorting
http://www.graphviz.org/Resources.php
http://graphml.graphdrawing.org/
http://habrahabr.ru/blogs/python/125003/#habracut Dejkstra+Python
http://habrahabr.ru/blogs/python/112421/ Graphs in Python
https://en.m.wikipedia.org/wiki/Depth-first_search
http://www.programcreek.com/2012/12/leetcode-solution-for-binary-tree-preorder-traversal-in-java/
https://changhaz.wordpress.com/2014/04/24/leetcode-binary-tree-maximum-path-sum/
struct Node{
int data;
struct Node* left;
struct Node* right;
};
int getBinaryTreeHeight(struct Node* root){
if (root == NULL) return 0;
int leftHeight = getBinaryTreeHeight(root->left);
int rightHeight = getBinaryTreeHeight(root->right);
return 1 + (leftHeight <= rightHeight ? rightHeight : leftHeight);
}
Trees
https://en.wikipedia.org/wiki/Tree_traversal
http://habrahabr.ru/post/150732/ AVL tree
http://habrahabr.ru/post/151421/ Prefix tree
Balanced tree
http://habrahabr.ru/post/66926/ Balanced trees
https://medium.com/omarelgabrys-blog/balanced-search-trees-68a95ba91f50#.au56nft7y
http://ayende.com/blog/162945/b-trees-and-why-i-love-them-part-i B-trees
find if tree is sub-tree of another tree
Print path from root to destination node
http://algorithms.tutorialhorizon.com/print-a-path-from-root-to-node-in-binary-tree/
public static ArrayList path;
public Boolean printPath(Node root, Node dest){
if(root==null) return false;
if(root==dest||printPath(root.left,dest)||printPath(root.right,dest)){
path.add(root.data);
return true;
}
return false;
}
Lowest common ancestor in BST
https://www.youtube.com/watch?v=TIoCCStdiFo&feature=youtu.be
https://www.youtube.com/watch?v=NBcqBddFbZw&list=PLamzFoFxwoNjPfxzaWqs7cZGsPYy0x_gI
Start will the root.
If root>n1 and root>n2 then lowest common ancestor will be in left subtree - make recursion call.
If root<n1 and root<n2 then lowest common ancestor will be in right subtree - make recursion call .
If Step 2 and Step 3 is false then we are at the root which is lowest common ancestor, return it.
Lowest common ancestor in regular BT
http://algorithms.tutorialhorizon.com/lowest-common-ancestor-in-a-binary-tree-not-binary-search-tree/
http://articles.leetcode.com/lowest-common-ancestor-of-a-binary-tree-part-ii/
Method 1
1) Find path from root to n1 and store it in a vector or array.
2) Find path from root to n2 and store it in another vector or array.
3) Traverse both paths till the values in arrays are same. Return the common element just before the mismatch.
Method 2 - single path:
Node find(Node root, Node a, Node b) {
if (root == NULL or a==root or b == root ) return root;
Node left = find(root->left,a,b)
Node right = find(root->right,a,b)
if (left && right)
return root
else if left
return left
else
return right
}
Following in binary tree but not binary search tree
10 / \ 5 15 -------- binary tree ... but not a binary search tree / \ 6 20
For tree above the post order traversal is: https://www.youtube.com/watch?v=xLQKdq0Ffjg
5 , 6, 20, 15, 10
For any given node in BT to check if it is BST, we need to check that
-it is in between its children
-not greater than its smallest right parent or smaller than it's biggest left parent:
http://www.programcreek.com/2012/12/leetcode-validate-binary-search-tree-java/
boolean isBSTorNot(BinaryNode<T> n) {
return isBST(n, T.MIN_VALUE, T.MAX_VALUE);
}
boolean isBST(BinaryNode<T> n, T min, T max) {
if(! (n.value <= n.right.value && n.value >= n.left.value && n.value >= min && n.value <= max) ) {
return false;
}
return isBST(n.left, min, n.value) && isBST(n.right, n.value, max)
}
B+ trees
http://en.wikipedia.org/wiki/GiST
http://zgking.com:8080/home/donghui/publications/books/dshandbook_BTree.pdf
http://www.codeproject.com/KB/database/btreedbclass.aspx
http://google-opensource.blogspot.com/2013/01/c-containers-that-save-memory-and-time.html
int getBinaryTreeHeight(struct Node* root)
{
if (root == NULL)
return 0;
int leftHeight = getBinaryTreeHeight(root->left);
int rightHeight = getBinaryTreeHeight(root->right);
return 1 + (leftHeight <= rightHeight ? rightHeight : leftHeight);
}
There are three different types of depth-first traversals, preorder, inorder, and postorder
Inorder (left, node, right) traversal for BST prints the sorted node values
Postorder traversal could be use to evaluate the expression tree where the parent node is operation like +
void writeBinaryTree(BinaryTree *p, ostream &out) {
if (!p) {
out << "# ";
} else {
out << p->data << " ";
writeBinaryTree(p->left, out);
writeBinaryTree(p->right, out);
}
}
void readBinaryTree(BinaryTree *&p, ifstream &fin) {
int token;
bool isNumber;
if (!readNextToken(token, fin, isNumber))
return;
if (isNumber) {
p = new BinaryTree(token);
readBinaryTree(p->left, fin);
readBinaryTree(p->right, fin);
}
}
There is only one kind of breadth-first traversal--the level order traversal.
To implement a level-order traversal, we need a first-in first-out queue
http://www.leetcode.com/2010/09/printing-binary-tree-in-level-order.html
http://www.ibm.com/developerworks/aix/library/au-aix-stack-tree-traversal/index.html
https://workshape.github.io/visual-graph-algorithms/
#include< iostream >
#include"Queue.h"
struct BinaryTree{
int data;
BinaryTree *left;
BinaryTree *right;
} *root=NULL;
BreadthOrderTraversal(BinaryTree root){
Queue< BinaryTree *> Q;
BinaryTree temp;
Q.Enqueue(root);
while(!Q.isEmpty()){
temp = Q.Deque(); //Deque the topmost node of the tree
if (temp->left) Q.Enqueue(temp->left); //Enqueue if exists
if (temp->right) Q.Enqueue(temp->right); //Enqueue if exists
}
}
if we will use the stack instead queue in code above we will have Depth First Traversal:
DepthFirstInorderTraversal(Tree *p){
stack < Tree* > S;
do{
while (p!=NULL) {
S.push(p); // store a node in the stack
p=p->left; // visit it's left child
}
// If there are nodes in the stack to which we can move up then pop it
if (!S.empty()){
p=S.top();
S.pop();
cout << p->ele << "-"; // print the nodes value
p=p->right; // vistit the right child now
}
}while(!S.empty()||p!=NULL); // while the stack is not empty or there is a valid node
}
http://habrahabr.ru/post/259295/ Dikstra поиск кратчайших путей из данной вершины в графе.
Reverse singly-linked list
http://jasonroell.com/2015/07/06/every-programmer-should-understand-thi-s/
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
/ /using Recursion
public ListNode reverseList(ListNode head) {
if(head==null || head.next == null)
return head;
//get second node
ListNode second = head.next;
//set first’s next to be null head.next = null;
ListNode rest = reverseList(second);
second.next = head;
return rest;
}
// without using Recursion
public ListNode reverseList(ListNode head) {
if(head==null || head.next == null)
return head;
ListNode p1 = head;
ListNode p2 = head.next;
head.next = null;
while(p1!= null && p2!= null){
ListNode t = p2.next;
p2.next = p1;
p1 = p2;
if (t!=null){
p2 = t;
}else{
break;
}
}
return p2;
}
Reverse Linked List
http://www.leetcode.com/2010/04/reversing-linked-list-iteratively-and.html
#include <stdio.h>
typedef struct Node {
char data;
struct Node* next;
} Node;
void print_list(Node* root) {
while (root) {
printf("%c ", root->data);
root = root->next;
}
printf("\n");
}
Node* reverse(Node* root) {
Node* new_root = 0;
while (root) {
Node* next = root->next;
root->next = new_root;
new_root = root;
root = next;
}
return new_root;
}
int main() {
Node d = { 'd', 0 };
Node c = { 'c', &d };
Node b = { 'b', &c };
Node a = { 'a', &b };
Node* root = &a;
print_list(root);
root = reverse(root);
print_list(root);
return 0;
}
Intersection point of 2 Linked Lists
Find the length of both the linked list and check that they have the same tail node.
Find the difference in length (d)
For the longer LL, traverse d nodes and check the addresses with another LL
http://codesam.blogspot.com/2011/03/check-if-two-singly-linked-lists.html
If two singly linked list intersect, then End point must be same element!
So, in list1 you can keep move until you meet the null (last element),
then keep the previous node. Same work for list2.
Then compare end_node_list1, end_node_list2
Find if the linked list has a loop:
http://codesam.blogspot.com/2011/03/algorithm-to-determine-if-linked-list.html
http://www.geeksforgeeks.org/archives/112
Have 2 pointers moving with different speed
def has_loop?(node)
slow = node
fast = node
until slow.next.nil? or fast.next.nil? do
slow = slow.next
fast = fast.next.next
return true if (slow == fast)
end
false
end