Amazon Interview Question
Software Engineer / DevelopersIf level represents depth, then this computes horizontal sum :) but the idea is the same.
@airfang613 : it will print the vertical sum and not the horizontal, work with some example
void verticalSum( struct tree * root, int a[], int pivot)
{
if(root== NULL)
return;
a[pivot]= a[pivot] + root->data;
if( root->left)
{ pivot--;
verticalSum(root->left,a,pivot);
}
if( root->right)
{ pivot++;
verticalSum(root->right,a,pivot);
}
}
int main()
{
int a[100];
for(i= 0; i < 100; i++)
a[i] = 0;
vericalSum( root, a, 10);
}
My solution with a deque ....
deque<int> dq;
int cursor = -1; /* cursor is the index of current node in deque */
void GetVerticalSum( Node *root )
{
if ( root == NULL )
return ;
if ( cursor == -1 ) /* reach left , add elem in deque head */
{
dq.push_front ( root->data );
cursor = 0;
}
else if ( cursor == dq.size() ) /* reach right, add elem in deque tail */
dq.push_back( root->data );
else /* No need to add new elem in deque */
dq[ cursor ] += root->data ;
/* traversal */
if ( root->left )
{
cursor--;
GetVerticalSum( root->left );
cursor++;
}
if ( root->right )
{
cursor++;
GetVerticalSum( root->right );
cursor--;
}
}
create an array sum[] for storing the content.. initialised to 0
find the maximum depth of the tree...
make an inital call to fun(root,depth)
function fun is :
takes O(n) complexity ..
- sukhmeet July 22, 2011