Tree Algorithm Questions

Algorithm Series 4

Tree Algorithm Questions

Binary Search Tree Implementation in Java
Binary Heap Implementation
How to insert and delete from a binary search trees?
How to balance an AVL/red-black tree?
Preorder Traversal, No Recursion
void preorderTraversal( Node root ){
    Stack stack = new Stack();
    stack.push( root );
    while( true ){
        Node curr = stack.pop();
        if( curr == null ) break;
        curr.printValue();
        Node n = curr.getRight();
        if( n != null ) stack.push( n );
        n = curr.getLeft();
        if( n != null ) stack.push( n );
    }
}
1.Cursor <= root
2.While true
{    a.If cursor is not null;
              i.push in stack
              ii.Cursor <= left child of cursor
     b.end
     c.If Cursor is NULL
              i.Cursor <= top of stack
              ii.Pop from stack and print
              iii.Cursor <= Right child of cursor
     d.end
}
Push the root node to the child stack.
While child stack is not empty
Pop a node from the child stack, and push it to the parent stack.
Push its left child followed by its right child to the child stack.
Now the parent stack would have all the nodes ready to be traversed in post-order.
En-queue right child prior to left child during BFS, and put them into a stack, print the stack after BFS is done.
Check if a tree is balanced?
public static boolean isBalanced(TreeNode root){
  return (maxDepth(root) - minDepth(root) <= 1);
}
Check if a tree is binary search tree?
Check whether all node are starting at valid range of values allowed by the currentnode's ancestors.
boolean isValid(Node root) {
    return isValidHelper(root, Integer.MIN_VALUE,
                         Integer.MAX_VALUE);
}
boolean isValidHelper(Node curr, int min, int max) {
    if (curr.left != null) {
        if (curr.left.value < min ||
               !isValidHelper(curr.left, min, curr.value))
            return false;
    }
    if (curr.right != null) {
        if (curr.right.value > max ||
               !isValidHelper(curr.right, curr.value, max))
            return false;
    }
    return true;
}
Is a tree complete? [TODO]
Count number of nodes in the tree if they are less then k returns.
If (no_of_nodes(node->left) == k-1) return node->data
If (no_of_nodes(node->left) >= k) findkthmin(node->left,k)
else findkthmin(node->right, (k - no_of_nodes(node->left) -1))
Count ancestors for each of the nodes, the node whose number of ancestor is 0 is the root.
Set that node to null, and reconstruct ancestor count column and repeat above steps.
Given a sorted (increasing order) array, create a binary tree with minimal height
public static TreeNode addToTree(int arr[], int start, int end){
  if (end < start) {
    return null;
  }
  int mid = (start + end) / 2;
  TreeNode n = new TreeNode(arr[mid]);
  n.left = addToTree(arr, start, mid - 1);
  n.right = addToTree(arr, mid + 1, end);
  return n;
}
Given a binary search tree, create a linked list of all the nodes at each depth.
Find the next node (eg, in-order successor) of a given node in a binary search tree where each node has a link to its parent
public static TreeNode inorderSucc(TreeNode e) {
  if (e != null) {
    TreeNode p;
    // Found right children -> return 1st inorder node on right
    if (e.parent == null || e.right != null) {
      p = leftMostChild(e.right);
    } else {
      // Go up until we’re on left instead of right (case 2b)
      while ((p = e.parent) != null) {
        if (p.left == e) {
          break;
        }
        e = p;
      }
    }
    return p;
  }
  return null;
}
Inorder Successor in binary tree without parent pointer
http://tech-queries.blogspot.com/2010/04/inorder-succesor-in-binary-tree-wo.html
The trick is that whenever you go left in searching of that node, make the value of the variable as the value of the parent (I mean from where you go left).

Quasi-Isomorphic trees
Two trees s and t are quasi-isomorphic if s can be transformed into t by swapping left and right children of some of the nodes of s.
The values in the nodes are not important in determining quasi-isomorphism, only the shape is important.
return (quasiisomorphic(treeone->left, treetwo->left)
      && quasiisomorphic(treeone->right, treetwo->right)
      || quasiisomorphic(treeone->right, treetwo->left)
      && quasiisomorphic(treeone->left, treetwo->right));

Isomorphic trees
Two binary trees s and t are isomorphic if they have the same shape; the values stored in the nodes do not affect whether two trees are isomorphic.
return (isomorphic(treeone->left, treetwo->left)
       && isomorphic(treeone->right, treetwo->right));

Print all paths in a binary tree which sum up to that value
On every node, we look "up” to see if we’ve found the sum – bottom-up.
void findSum(TreeNode head, int sum, ArrayList buffer,
      int level) {
  if (head == null) return;
  int tmp = sum;
  buffer.add(head.data);
  for (int i = level;i >- 1; i--){
    tmp -= buffer.get(i);
    if (tmp == 0) print(buffer, i, level);
  }
  ArrayList c1 = (ArrayList) buffer.clone();
  ArrayList c2 = (ArrayList) buffer.clone();
  findSum(head.left, sum, c1, level + 1);
  findSum(head.right, sum, c2, level + 1);
}
Decide if T2 is a subtree of T1 - O(nm)
boolean containsTree(TreeNode t1, TreeNode t2) {
  if (t2 == null) return true; // The empty tree is always a subtree
  else return subTree(t1, t2);
}
boolean subTree(TreeNode r1, TreeNode r2) {
  if (r1 == null)
    return false; // big tree empty & subtree still not found.
  if (r1.data == r2.data) {
    if (matchTree(r1,r2)) return true;
  }
  return (subTree(r1.left, r2) || subTree(r1.right, r2));
}
boolean matchTree(TreeNode r1, TreeNode r2) {
  if (r2 == null && r1 == null)
    return true; // nothing left in the subtree
  if (r1 == null || r2 == null)
    return false; //  big tree empty & subtree still not found
  if (r1.data != r2.data)
    return false;  // data doesn’t match
  return (matchTree(r1.left, r2.left) &&
      matchTree(r1.right, r2.right));
  }
}
Find the Lowest common ancestor of two nodes in a binary tree 
Solution 1:
If each node has a link to its parent, we could trace p and q’s paths up until they intersect
Solution 2:
Follow a chain in which p and q are on the same side. That is, if p and
q are both on the left of the node, branch left to look for the common ancestor. When p and q are no longer on the same side, you must have found the first common ancestor.
Sub-function: test whether a node is a child of another node - use recursion
Variant:
Find the first common ancestor of two nodes in a binary search tree
Node findLowestCommonAncestor( Node root, Node p1,
                               Node p2 ){
    while( root != null ){
        int value = root.getValue();
        int value1 = p1.getValue(), value2 = p2.getValue();
        if( value > value1 && value > value2 )
        {
            if(root.getLeft()==p1 || root.getLeft()==p2) return root;
            root = root.getLeft();
        } else if( value < value1 && value < value2 ){
            if(root.getRight()==p1 || root.getRight()==p2) return root;       
            root = root.getRight();
        } else {
            return root;
        }
   }
   return null;
}
Find a path between nodesina Binary Tree
The essence is to identify the lowestcommonancestor.
Huffman code
Always merge 2 least-frequent nodes and re-put it to the priority queue.
Minimum Spanning Tree algorithm
Prim's algorithm
The set A forms a single tree. The safe edge added to A is always a least-weight edge connecting the tree to a vertex not in the tree.
The tree starts from an arbitrary root vertex r.
At each step with an edge that contributes the minimum amount possible to the tree's weight.

Resources
Post a Comment

Labels

Java (159) Lucene-Solr (110) Interview (61) All (58) J2SE (53) Algorithm (45) Soft Skills (36) Eclipse (34) Code Example (31) Linux (24) JavaScript (23) Spring (22) Windows (22) Web Development (20) Nutch2 (18) Tools (18) Bugs (17) Debug (15) Defects (14) Text Mining (14) J2EE (13) Network (13) PowerShell (11) Troubleshooting (11) Chrome (9) Design (9) How to (9) Learning code (9) Performance (9) UIMA (9) html (9) Http Client (8) Maven (8) Problem Solving (8) Security (8) bat (8) blogger (8) Big Data (7) Continuous Integration (7) Google (7) Guava (7) JSON (7) ANT (6) Coding Skills (6) Database (6) Scala (6) Shell (6) css (6) Algorithm Series (5) Cache (5) Dynamic Languages (5) IDE (5) Lesson Learned (5) Programmer Skills (5) Tips (5) adsense (5) xml (5) AIX (4) Code Quality (4) GAE (4) Git (4) Good Programming Practices (4) Jackson (4) Memory Usage (4) Miscs (4) OpenNLP (4) Project Managment (4) Spark (4) System Design (4) Testing (4) ads (4) regular-expression (4) Android (3) Apache Spark (3) Become a Better You (3) Concurrency (3) Eclipse RCP (3) English (3) Happy Hacking (3) IBM (3) J2SE Knowledge Series (3) JAX-RS (3) Jetty (3) Restful Web Service (3) Script (3) regex (3) seo (3) .Net (2) Android Studio (2) Apache (2) Apache Procrun (2) Architecture (2) Batch (2) Bit Operation (2) Build (2) Building Scalable Web Sites (2) C# (2) C/C++ (2) CSV (2) Career (2) Cassandra (2) Distributed (2) Fiddler (2) Firefox (2) Google Drive (2) Gson (2) How to Interview (2) Html Parser (2) Http (2) Image Tools (2) JQuery (2) Jersey (2) LDAP (2) Life (2) Logging (2) Python (2) Software Issues (2) Storage (2) Text Search (2) xml parser (2) AOP (1) Application Design (1) AspectJ (1) Chrome DevTools (1) Cloud (1) Codility (1) Data Mining (1) Data Structure (1) ExceptionUtils (1) Exif (1) Feature Request (1) FindBugs (1) Greasemonkey (1) HTML5 (1) Httpd (1) I18N (1) IBM Java Thread Dump Analyzer (1) JDK Source Code (1) JDK8 (1) JMX (1) Lazy Developer (1) Mac (1) Machine Learning (1) Mobile (1) My Plan for 2010 (1) Netbeans (1) Notes (1) Operating System (1) Perl (1) Problems (1) Product Architecture (1) Programming Life (1) Quality (1) Redhat (1) Redis (1) Review (1) RxJava (1) Solutions logs (1) Team Management (1) Thread Dump Analyzer (1) Visualization (1) boilerpipe (1) htm (1) ongoing (1) procrun (1) rss (1)

Popular Posts