Rotate image (square matrix) by 90 deg
Tue, 06 May 2025
Given a binary tree and a number n representing the vertical level.
Write code to compute the sum of all nodes which are at vertical level n.
For example, if the binary tree given is as below:
and n=-1, then the output should be 12. Because Nodes at level =1 are 7 and 5 and 7+5 = 12.
Code:
// n - level whose sum we want to compute.
// curLevel - vertical level of current node.
int sumOfVerticalLevel(Node *r, int curLevel, int n)
{
if(r == NULL)
return 0;
int sum = 0;
if(curLevel == n)
sum += r->data;
// Adding all nodes in left subtree at
// vertical level n
sum += sumOfVerticalLevel(r->left, curLevel-1, n);
// Adding all nodes in right subtree at
// vertical level n
sum += sumOfVerticalLevel(r->right, curLevel+1, n);
return sum;
}
The initial value of curLevel is zero (current level or root node). The time taken by this function is O(n).
Tue, 06 May 2025
Tue, 06 May 2025
Tue, 06 May 2025
Leave a comment