Monday, November 28, 2016

#codingexercise
Implement AVL tree insertion
Node Insert(ref Node root, Node z)
{
assert(z);
z.height = -1;
if (!root)
     root = z;
else if (z.data < root.data)
     root.left = Insert(root.left, z);
else
     root.right = Insert(root.right, z);

root.height = 1 + max(height(root.left), height(root.right));
Balance(root);
}

Node Balance(Node root)
{
FixHeight(root); // 1 more than left or right
if (Bfactor(root) == 2) // Bfactor is h(right)-h(left)
{
      if (Bfactor(root.right) < 0)
           root.right = RightRotate(root.right); // returns root.right.left
      return LeftRotate(root);
}
if(BFactor(root) == -2)
{
      if (Bfactor(root.left) > 0)
           root.left = LeftRotate(root.left);
      return RightRotate(root);
}
return root;
}
Courtesy : https://kukuruku.co/hub/cpp/avl-trees, the wrong implementation in GeeksforGeeks and my fixes to that implementation.

// BST Tree insert iterative
TREE-INSERT(ref Node root, Node z)
{
Node y = null;
Node x = root;
while (x != null)
{
     y = x;
     if (z.data < x.data)
        x = x.left;
     else
        x = x.right;
}
if (y == null)
    root = z;
else if (z.data < y.data)
            y.left = z;
       else
            y.right = z;
}

string reversal recursive:
string reverse(string input)
{
var chars = input.ToChars();
var rev = chars.Aggregate((sent, next) =>  next + sent);
return rev.ToString();
}


No comments:

Post a Comment