文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
Binary Tree Tilt2. Solution
/**
* 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;
dfs(root, tilt);
return tilt;
}
private:
int dfs(TreeNode* root, int& tilt) {
if(!root) {
return 0;
}
int leftSum = dfs(root->left, tilt);
int rightSum = dfs(root->right, tilt);
tilt += abs(leftSum - rightSum);
return root->val + leftSum + rightSum;
}
};
网友评论