Popular Posts

Friday, February 4, 2011

Diameter of a Binary Tree

Tree Diameter :The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two leaves in the tree.The diameter of G is defined as being the maximal distance in the graph.
The diameter of a tree T is the largest of the following quantities :
* the diameter of T’s left subtree
* the diameter of T’s right subtree
* the longest path between leaves that goes through the root of T (this can be computed

/* Function to get diameter of a binary tree */
int diameter(struct node * tree)
{
   /* base case where tree is empty */
   if (tree == 0)
     return 0;
  /* get the height of left and right sub-trees */
  int lheight = height(tree->left);
  int rheight = height(tree->right);
  /* get the diameter of left and right sub-trees */
  int ldiameter = diameter(tree->left);
  int rdiameter = diameter(tree->right);
  /* Return max of following three
   1) Diameter of left subtree
   2) Diameter of right subtree
   3) Height of left subtree + height of right subtree + 1 */
  return max(lheight + rheight + 1, max(ldiameter, rdiameter));
}
Refer :  http://geeksforgeeks.org/?p=5687


Thursday, February 3, 2011

Foldable Binary trees

Given a binary tree,find whether it can be foldable or not :
A tree can be folded if left and right subtrees of the tree are structure wise mirror image of each other. An empty tree is considered as foldable.
Algorithm : we can do this using recursion.
1.If the root is null,then it is foldable.
2.else check left and right branches recursively.
recursion function :
if left and right both are null,then return true.
if one branch is null while other branch is not null,return false.(asymmetric)
bool isFoldable (node* root) {
if (!root) return true;
return areMirrorImages(root->left, root->right);
}

bool areMirrorImages (node* leftTree, node* rightTree) {
if (!leftTree && !rightTree)
return true;
if (!leftTree && rightTree)
return false;
if (!rightTree && leftTree)
return false;

return areMirrorImages (leftTree->left, rightTree->right) && areMirrorImages (leftTree->right, rightTree->left);
}
Do the same thing for left and right branches.
Refer : http://geeksforgeeks.org/?p=7956

Convert Binary tree into Linked list

Structure of nodes in both doubly linked list and binary search tree are same.So we need to arrange the pointers among the nodes.We can use recursive algorithm to convert BST to doubly linked list.

Algorithm :


An ordered binary tree looks like below:




a circular/doubly linked list looks like this.
if we remove the link in first node and last node of a circular linked list,t will become a doubly linked list.


Recursive algorithm which takes BST and rearranges the internal pointers to make a circular doubly linked list.The list should be arranged so that the nodes are in increasing order. Return the head pointer to the new list.






Algorithm:

If tree is not empty
Convert left subtree to List, let hLeft points to it
Convert right subtree to List, let hRight points to it
Append hLeft with root and then hRight
For detailed explanation have a look at this link :
http://www.rawkam.com/?p=1139


Convert linked list into binary search tree:
If it sorted list,we can do the reverse engineering from conversion of tree to linked list.

If the list is not empty.
 Middle element of the list will become root of the element.
Recursively construct the BST from left and right parts of the linked list.Left and right parts of list will become left and right branches of tree.

In place conversion of sorted doubly linked list to balanced BST : http://www.geeksforgeeks.org/archives/17629

Sorted linked list to balanced BST : http://www.geeksforgeeks.org/archives/17063

Wednesday, February 2, 2011

Java virtual machine

To get better understanding about internal architecture of Java virtual machine,go through below link:
http://www.artima.com/insidejvm/ed2/jvmP.html

Combination of a string

Algorithm :

Step 1: Add the String to the combination results.
Step 2: If the String has just one character in it,
then stop the current line of execution.
Step 3: Create new sub-words from the String by removing one letter at a time.
If the String is "ABCD", form sub-words like "BCD", "ACD", "ABD", "ABC"
Step 4: For each of the sub-word, go to Step 1


    Java program :
     import java.util.HashSet;
    import java.util.Set;

    /**
    * A simple program that generates all possible combinations for a given String
    * using recursion.
    */
    public class StringCombinations {
    // A set to hold the generated combination results.
    private Set<String> combinations = new HashSet<String>();

    /**
    * The constructor.
    *
    * Simply makes a call to the generate method to generate all the possible
    * combinations of the String "wxyz"
    */
    public StringCombinations(String sInputString) {
    generate(sInputString);
    System.out.println("*** Generated " + combinations.size()
    + " combinations ***");
    System.out.println(combinations);
    }

    /**
    * The recursive method does the work of generating all the possible
    * combinations for a given String.
    */
    public void generate(String word) {
    // Add this word to our combination results set
    combinations.add(word);

    // If the word has only one character we break the recursion
    if (word.length() == 1) {
    combinations.add(word);
    return;
    }
    // Go through every position of the word
    for (int i = 0; i < word.length(); i++) {
    // Remove the character at the current position
    // all call this method with that String (Recursion!)
    generate(word.substring(0, i) + word.substring(i + 1));
    }
    }

    /**
    * Entry point to this program. Instantiates the StringCombinations program.
    *
    */
    public static void main(String args[]) {
    String sInputString = "abcd";
    new StringCombinations(sInputString);
    }

    }

    Tuesday, February 1, 2011

    Permutations of a given string

    In outline form,algorithm looks like :

    If you're past the last position
    Print the string
    Return
    Otherwise
    For each letter in the input string
    If it's marked as used, skip to the next letter
    Else place the letter in the current position
    Mark the letter as used
    Permute remaining letters starting at current position + 1
    Mark the letter as unused

    Recursive Implementation :
    Java code:
    public class Permutations {

    public static void main(String[] args) {
    permutation("", "abc");
    }

    private static void permutation(String prefix, String str) {
    int n = str.length();
    if (n == 0)
    System.out.println(prefix);
    else {
    for (int i = 0; i < n; i++)
    permutation(prefix + str.charAt(i), str.substring(0, i)
    + str.substring(i + 1, n));
    }
    }
    }


    Method 2:
    import java.util.ArrayList;
    import java.util.List;

    public class Permutations {

    public static void main(String[] args) {
    List<String> permutations = getPermutations("abcd");
    System.out.println(" size " + permutations.size());
    for (int i = 0; i < permutations.size(); i++) {
    System.out.println(permutations.get(i));
    }
    }

    public static List<String> getPermutations(String word) {
    if (word == null || word.length() == 0)
    throw new NullPointerException();
    ArrayList<String> result = new ArrayList<String>();
    if (word.length() == 1) {
    result.add(word);
    return result;
    }
    List<String> temp = getPermutations(word
    .substring(0, word.length() - 1));
    for (String s : temp) {
    List<String> joined = joinCharToString(s, word
    .charAt(word.length() - 1));
    result.addAll(joined);
    }
    return result;
    }

    public static List<String> joinCharToString(String ori, char aChar) {
    if (ori == null || ori.length() == 0)
    throw new NullPointerException();
    List<String> result = new ArrayList<String>();
    StringBuilder sb;
    for (int i = 0; i < ori.length() + 1; i++) {
    sb = new StringBuilder(ori);
    sb.insert(i, aChar);
    result.add(sb.toString());
    }
    return result;
    }
    }

    Print all permutations with repetition of characters : 
    Given a string of length n, print all permutation of the given string. Repetition of characters is allowed. Print these permutations in lexicographically sorted order
    Examples:
    Input: AB
    Ouput: All permutations of AB with repetition are:
          AA
          AB
          BA
          BB
    Java Code : 
    public class Permutations {
    public static void main(String[] args) {
    String str = "abc";
    char[] chars = str.toCharArray();
    getPermutations(chars, "", str.length());
    }

    private static void getPermutations(char[] chars, String target, int length) {
    if (length == 0) {
    System.out.println(target);
    return;
    }

    for (int i = 0; i < chars.length; i++) {
    getPermutations(chars, target + chars[i], length - 1);
    }
    }
    }