https://leetcode.com/problems/binary-tree-tilt/#/description
这题挺简单的但要理解对tilt是关键,某个节点的tilt是指该节点左子树的所有节点的和、右子树所有节点的和,这两个值的差的绝对值。下面是小弟的算法
/**
* 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) {
int rightVal;
int leftVal;
if(root == NULL){
return 0;
}
leftVal = findTilt(root->left);
rightVal = findTilt(root->right);
int leftSum = sum(root->left);
int rightSum = sum(root->right);
int relaVal = abs(leftSum - rightSum);
int result = leftVal + rightVal + relaVal;
return result;
}
int sum(TreeNode* root){
if(root == NULL){
return 0;
}
int leftSum = sum(root->left);
int rightSum = sum(root->right);
int sumVal = leftSum + rightSum + root->val;
return sumVal;
}
};