National Instruments Interview Question
Software Engineer / Developersvoid average(node *Start)
{
static int result=0;
static int count=0;
int average=0;
if(start !=null)
{
average(Start->left);
result+=Start->data;
count++;
average(Start->right);
}
average=(result)/count;
}
struct node
{
int info;
struct node *link;
}
typedef struct node *NODE;
void average(NODE first)
{
NODE temp;
temp=first;
int sum=0,n=0;
float avg=0.0;
do
{
sum=sum+temp->info;
temp=temp->link;
n++;
}
while(temp->link!=NULL)
avg=sum/n;
printf("average = %f",avg);
}
}
public float meanvalue(int[] graph, int i)
{
float mean = 0 ;
int count = 0 ;
for all node in graph{
node.visit = false;
}
stack.push(i);
while(!stack.empty())
{
p <- stack.pop()
if(p is not visited)
{
visited[p] = true;
count++ ;
mean = mean + p.value;
for each neighbor p:
stack.push(p.neighbor)
}
}
mean = mean/ count;
return mean;
}
int CalculateAverage(stTree* pRoot)
{
int nCount = 0;
return CalculateSumNCount(pRoot,nCount)/nCount;
}
int CalculateSumNCount(stTree* pRoot,int& count)
{
if(pRoot == NULL)
return 0;
count++;
return (pRoot->data + CalculateSumNCount(pRoot->left,count) + CalculateSumNCount(pRoot->right,count));
}
We can use a recursive function along with static storage for the summation such that value is retained between successive call to the function.
- veb October 17, 2010This method first computer over left subtree and then on right subtree of the Root of the binary tree.. static specifier maintain the value between recursive calls..
void average(node* start)
{
static int average = 0;
if(start!= NULL)
{
Add(node->left);
Add(node->right);
result += node->value;
}
}