# Problem

Given a binary tree, 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 node has tilt 0.

The tilt of the whole tree is defined as the sum of all nodes’ tilt.

## Note

• The sum of node values in any subtree won’t exceed the range of 32-bit integer.
• All the tilt values won’t exceed the range of 32-bit integer.

# Solution1

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int findTilt(TreeNode* root) {
if(!root)
return 0;
int leftTilt = findTilt(root->left);
int rightTilt = findTilt(root->right);
int rootTilt = abs(treeSum(root->left) - treeSum(root->right));

return leftTilt+rootTilt + rightTilt;

}
int treeSum(TreeNode* root)
{
if(!root)
return 0;
return root->val + treeSum(root->left) + treeSum(root->right);
}
};


# Solution2

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int findTilt(TreeNode* root) {
if(!root)
return 0;
int tilt = 0;
treeSum(root,tilt);
return tilt;

}
int treeSum(TreeNode* root,int& tilt)
{
if(!root)
return 0;
int leftSum = treeSum(root->left,tilt);
int rightSum = treeSum(root->right,tilt);
tilt += abs(leftSum - rightSum);
return root->val + leftSum + rightSum;
}
};


©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客