leetcode链接:https://leetcode.cn/problems/binary-tree-tilt/description/
代码:
class Solution {
public:
int childFind(TreeNode* root , int& sumTile) {
if (root == nullptr) {
return 0; // 空树坡度为0
}
int leftChildVal = childFind(root->left , sumTile);
int rightChildVal = childFind(root->right , sumTile);
sumTile += abs(leftChildVal - rightChildVal);
return root->val + leftChildVal + rightChildVal;
}
int findTilt(TreeNode* root) {
int sumTile = 0;
childFind(root , sumTile);
return sumTile;
}
};