 Tilt of Binary Tree
Submissions: 3345   Accuracy: 54.75%   Difficulty: Easy   Marks: 2

Given a binary tree of size N+1, your task is to complete the function tiltTree(), that return the tilt of the whole tree. The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null nodes are assigned tilt to be zero. Therefore, tilt of the whole tree is defined as the sum of all nodes’ tilt.

Examples:

Input :
1
/ \
2   3
Output : 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1

Input :
4
/ \
2   9
/ \   \
3   5   7
Output : 15
Explanation:
Tilt of node 3 : 0
Tilt of node 5 : 0
Tilt of node 7 : 0
Tilt of node 2 : |3-5| = 2
Tilt of node 9 : |0-7| = 7
Tilt of node 4 : |(3+5+2)-(9+7)| = 6
Tilt of binary tree : 0 + 0 + 0 + 2 + 7 + 6 = 15

Input:
The function takes a single argument as input, the reference pointer to the root of the binary tree.
There will be T test cases, and for each test case the function will be called separately.

Output:
For each test case output the tilt of the binary tree on a new line.

Constraints:
1<=T<=100
0<=N<=500

Example:
Input:

2
2
1 2 L 1 3 R
5
10 20 L 10 30 R 20 40 L 20 60 R 30 90 L
Output:
1
110

** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Harshit Sidhwa
Author: harshitsidhwa

If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.

Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.

to report an issue on this page.