2
* Definition for a binary tree node.7
* TreeNode() : val(0), left(nullptr), right(nullptr) {}8
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}9
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),15
/* We will take help of recursion16
Each function call will return the sum of subtree with root as current17
root and the tilt sum will be updated in the variable passed as reference20
int getTiltSum(TreeNode *root, int &tiltSum) {24
if (root->left == NULL and root->right == NULL) { // If we have a leaf25
tiltSum += 0; // Add nothing to tilt sum26
return root->val; // return its value as sum29
int leftSubTreeSum = getTiltSum(root->left, tiltSum); // Sum of all nodes in left30
int rightSubTreeSum = getTiltSum(root->right, tiltSum); // and right subtrees32
tiltSum += abs(leftSubTreeSum - rightSubTreeSum); // Update the tilt sum34
// return the sum of left Subtree + right subtree + current node as the sum36
return (root->val + leftSubTreeSum + rightSubTreeSum); // subtree with root as current node.39
int findTilt(TreeNode *root) {40
// variable to be passed as refrence and store the result43
getTiltSum(root, tiltSum);