思路:
用前序遍历,先从做底层开始往上面计算,但是在每一层换算的时候记录原来的root->val 最后计算根
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
int GetSum(TreeNode*root)
{
if(root==NULL)
return 0;
return GetSum(root->left)+GetSum(root->right)+root->val;
}
public:
int findTilt(TreeNode* root) {
if(root==NULL)
return 0;
return findTilt(root->left)+findTilt(root->right)+abs(GetSum(root->left)-GetSum(root->right));
}
};
如有错误,多多指教!