Sunday, June 5, 2016

We continue our previous posts with some more programming exercises
Given a binary tree find the vertical sum
void GetMinMaxHD(Node root, ref int min, ref int max, int hd)
{
if (root == null) return;
if (hd < min) min = hd;
if (hd > max) max = hd;
GetMinMaxHD(root.left, ref min, ref max, hd-1);
GetMinMaxHD(root.right, ref min, ref max, hd+1);
}
void GetVerticalLine(Node root, int linenum, int hd, ref List<int> line)
{
if (root == null) return;
if (hd == linenum) line.add(root);
GetVerticalLine(root.left, linenum, hd-1, ref line);
GetVerticalLine(root.right, linenum, hd+1, ref line);
}
List<int> verticalSum(node root)
{
var ret = new List<int>();
if (root == null) return null;
int min =0;
int max = 0;
GetMinMaxHD(Node root, ref min, ref max, 0);
for (int linenum = min; linenum <= max; linenum++)
{
  var line = new List<int>();
  GetVerticalLine(root, linenum, 0, ref line);
  ret.Add(line.sum());
}
return ret;
}

Print sorted from a matrix which is rowwise and columwise sorted
void PrintSorted(int[,] m, int rows, int cols, int r, int c, ref List<int>sorted)
{
int left = GetMinColumn(m, c+1); // extract min and replace with INT_MAX;
int down = GetMinRow(m, r+1); // extract min and replace with INT_MAX;
if (left == down && left == INT_MAX) // finished
    return;
if (left < down)
sorted.Add(left);
else
sorted.Add(down);
}

No comments:

Post a Comment