Amazon Interview Question
Software Engineer / DevelopersCreate a doubly linked list.
Do any order(pre, in, or post order) traversal and while we move left in the tree add the value in the current node to the current node in the doubly linked list and move left and vice versa for the right movement.
Now the final values in the doubly linked list will contain the sum values.
Also if we know the width of the tree, we can then create a integer array and then start from the root of the tree and corresponding index of the root in the tree width. then add the value in the root to the array[index]. Now if you move left decrement index or if you move right increment index.
now the final array will have the vertical sum of the tree.
just do like this way and u will find solution here :)
void verticalSum(struct node *R,int level,int sum[])
{
if(!R)
return;
sum[level]=sum[level]+R->data;
verticalSum(R->left,level-1,sum);
verticalSum(R->right,level+1,sum);
}
but first you have to find the no of levels at the left of the root node
for this to be done u can
int Nofleft(struct node *R)
{
if(!R)
return 0;
else
return(Noleft(R->right)+1);
}
}
and thus where u called this ucan then pass and call vertical sum by passing level=level+no of nodes at the left of the root node
i think it is prety easy :)
{
- vaibhav.iit2002 March 25, 2010public int sumNodeLevels(Node node, int level){
if(node != null){
int result = ++level;
// System.out.println("Node - " + node.info + ", " + level);
result += sumNodeLevels(node.left, level);
result += sumNodeLevels(node.right, level);
return result;
}
return 0;
}
}