Boundary Sum Problem Statement
Given a Binary Tree with 'N' nodes, compute and return the sum of all its boundary nodes. The boundary nodes include the root node, leftmost external nodes, rightmost external nodes, and all the leaves of the tree.
Explanation:
In the provided binary tree example, we have the following boundary nodes:
- Root: 2
- Leftmost: 35
- Rightmost: 10
- Leaf nodes: 2, 3, 5, 2
The total sum of these nodes would be 59.
Input:
The first line contains an integer 'T' denoting the number of test cases. Each test case consists of a single line containing the elements of the tree in level order, separated by a space. Use -1 for nonexistent children.
Output:
For each test case, output a single integer representing the sum of the boundary nodes. Each output should be on a new line.
Example:
Tree nodes in level order:
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
For this tree, the boundary nodes are formed as follows:
- Root: 1
- Leftmost: 2
- Rightmost: 3
- Leaf nodes: 4, 5, 6, 7
Boundary sum would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
Constraints:
- 1 <= T <= 100
- 1 <= N <= 1000
- -106 <= node.data <= 106
- Each node data value is bounded within the range from -106 to 106.
- Time Limit: 1 second
Note:
You do not need to print anything explicitly. Just implement the function as required.
Be the first one to answer
Add answer anonymously...
Top ThoughtWorks Software Engineer interview questions & answers
Popular interview questions of Software Engineer
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