思路:
- 递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int findTilt(struct TreeNode* root) {
int count = 0;
findTilt1(root,&count);
return count;
}
int findTilt1(struct TreeNode* root ,int *count){
if (root == NULL) {
return 0;
}
int left = 0;
int right = 0;
if(root->left == NULL && root->right == NULL) {
return root->val;
}
left = findTilt1(root->left,count);//左右子树求和
right = findTilt1(root->right,count);
*count = *count + abs(left - right);//求差之和
return left+right+root->val;//求各个树节点之和
}