?链接:
563. 二叉树的坡度
题解:
/**
* 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 {
public:
int findTilt(TreeNode* root) {
int sum = 0;
dfs(sum, root);
return sum;
}
int dfs(int& sum, TreeNode* root) {
if (!root) {
return 0;
}
int left = dfs(sum, root->left);
int right = dfs(sum, root->right);
sum += abs(left-right);
return left+right+root->val;
}
};
|