Monday, April 9, 2018

#InterestingCodingExercise
We are given a level wise serialized binary tree without level sentinels where null node is denoted by "#" and represented by an integer otherwise. The integer is a positive weight associated with that node and does not represent its identifier. The indices of the serialization array may be used as the node's identifier, if necessary. We need to extract the sum of all weights where no two weights are related directly. A node is related if it is in adjacent levels. This criteria may be dependent on the problem setter. For example, not directly related could also mean the node is neither the left nor the right for the node above. We will use the level criteria here:

static int findMax(String tree, int n)
{
        String[] elements = tree.split("\\s+");
        int maxLevel = (int)(Math.log(elements.length+1) / Math.log(2));
        int sums[] = new int[maxLevel];
        long odd = 0;
        long even = 0;
        for (int level = 0; level < maxLevel; level++) {
            
            for (int i = (int)Math.pow(2, level)-1; i < Math.pow(2, level+1)-1; i++) {
                // this assumes a full level otherwise we could go with previous level elements
                if (!elements[i].equals("#")) {
                    sums[level] += Integer.parseInt(elements[i]);
                }
            }
            
        }
        for (int i = 0; i < sums.length; i++)
        {
            if (i%2 == 0){
                even += sums[i];
            }else{
                odd += sums[i];
            }
        }

        return odd > even ? odd : even;
}

     3
  4     5
3   1   3

we get result as 9.   

if we do not have full representation at each level, we can use the following:
int start = 0;
int end = 0;
int prev = 0;
int current = 0;
for (int i = 0; i < elements.length; i++)
{
if (i == 0) { start = 1; end = 3; continue;}
if (i == end - 1) { start = end; end = start + 2 * prev; prev = 0;}
if ( nodes[current].left == INT_MIN) {
      if (elements[i] == "X") {
           nodes[current].left = INT_MAX;
      } else {
          nodes[current].left == -1;
          prev++;
      }
}
if ( nodes[current].left != INT_MIN && nodes[current].right == INT_MIN) {
      if (elements[i] == "X") {
           nodes[current].right = INT_MAX;
      } else {
           nodes[current].right = 1;
           prev++;
      }
      current++;

}
}

No comments:

Post a Comment