Diagonal Sum of Binary Tree
You are given a binary tree with 'N' nodes. Your task is to find and return a list containing the sums of all the diagonals of the binary tree, computed from right to left.
Input:
The input consists of a single line of integers representing the binary tree in level order. Each integer represents the value of a node in the tree, and '-1' indicates a null node.
Output:
Output a single line containing the sums of all diagonals from the rightmost diagonal to the leftmost diagonal, space-separated.
Example:
Consider the binary tree given below:
Input: 1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output:
24 14 2
Explanation:
The rightmost diagonal contains the elements {5, 10, 9} with a sum of 24. The middle diagonal contains {6, 3, 5} with a sum of 14. The leftmost diagonal only contains element {2} with a sum of 2.
Constraints:
- 0 <= N <= 10^5
- 0 <= node.data <= 10^9
- Time Limit : 1 second
Be the first one to answer
Add answer anonymously...
Top TCS Software Developer interview questions & answers
Popular interview questions of Software Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app