Saturday, August 27, 2016

#codingexercise
Get the maximum height of a common subtree between two binary trees.
There are a few ways to solve this problem such as evaluate each node to be root of a common subtree between both binary trees.
However, we know that when a subtree is common to both binary trees, all the elements in the sub tree will serialize into the same sequence for both binary trees. At that point, the problem decomposes to finding longest common substring between string representations of tree serializations.
void GetMaxHeightCommonSubTree(node tree1, node tree2)
{
var str1 = tree1.serialize();
var str2 = tree2.serialize();
var pattern =GetLCS(str1, str2);
var subtree = pattern.deserialize();
return GetMaxHeight(subtree);
}
string GetLCS(string str1, string str2)
{
   int end = 0
   int length = 0;
   var lcs = new int[str1.count, str2.count]();
    for (int i = 0; i < str1.length; i++)
       for (int j = 0; j < str2.length; j++)
        {
            if (i == 0 || j == 0) lcs[i,j] = 0;
            else if (str1[i-1] == str2[j-1]){
                    end = i;
                    lcs[i,j] = lcs[i-1,j-1] + 1;
                    length = max(length, lcs[i,j]);
            }
            else lcs[i,j] = 0;
         }
    return str1.substring(end-length+1, length);
}

2) Find if there is a  path from root to leaf in a binary tree with a given sum

bool hasPathSum(node root, int sum)
{
if (root == null) return sum == 0;
bool ret = false;
if (sum-root.data == 0 && root.left == null && root.right == null) return true;
if (root.left)
    ret = ret || hasPathSum(root.left, sum- root.data);
if (root.right)
   ret = ret || hasPathSum(root.right, sum -root.data);
return ret;
}

3) the serialization of a binary tree can be level order traversal

No comments:

Post a Comment