Wednesday, October 1, 2014

#codingexercise
Check if there's a path from root to leaf in a binary tree such that the sum of the node values equals the given number:
bool hasPathSumRecursive(Node root, int val, int sum = 0)
{
  if (root != null)
  {
    if (sum  + root.data > val) return false;
    return hasPathSumRecursive(root.left, val, sum+ root.data) || hasPathSumRecursive(root.right, val, sum+root.data);
   }
  return sum == val;
}
Now list all such paths :
bool hasPathSumRecursive(Node root, int val, int sum = 0, ref List<List<Node>> paths, ref List<Node> candidatePath)
{
  if (root != null)
  {
    candidatePath.Add(root);
    if (sum  + root.data > val) { candidatePath.Remove(root); return false;}
    bool hasPathSum =  hasPathSumRecursive(root.left, val, sum+root.data, paths, candidatePath) || hasPathSumRecursive(root.right, val, sum+ root.data, paths, candidatePath);
    if (hasPathSum)
       paths.Add(candidatePath);
    candidatePath.Remove(root);
    return hasPathSum;
   }
  return sum == val;
}

Concatenate two strings by removing the redundancy of the matching tail of one and the head of another

string ConcatenateTailHead(string t, string s)
{
   //parameter validation
   // canonicalization ( trim whitespace etc)
   int index = t.IndexOf(0, s[0]);
  while (index != -1 && index < t.Length)
 {
    if (s.startwith(t.substring(index))
    {
        return t.substring(0, index) + s;
     }
    index = t.IndexOf(s[0], index + 1);
 }
return t + s;
}

check if two trees are identical
bool isSameTree(Node a, node b)
{
 if (a == null || b == null)
{
 if (a != b) return false;
Else return true;
}
if (a.data != b.data)
{
 return false;
}
return isSameTree(a.left, b.left) && isSameTree(a.right, b.right);
}

No comments:

Post a Comment