https://leetcode-cn.com/problems/binary-tree-tilt/submissions/
给定一个二叉树,计算整个树的坡度。
一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值。空结点的的坡度是0。
整个树的坡度就是其所有节点的坡度之和。
示例:
输入:
1
/ \
2 3
输出: 1
解释:
结点的坡度 2 : 0
结点的坡度 3 : 0
结点的坡度 1 : |2-3| = 1
树的坡度 : 0 + 0 + 1 = 1
注意:
任何子树的结点的和不会超过32位整数的范围。
坡度的值不会超过32位整数的范围。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/*思路:
遍历节点采用后序遍历(计算左右子树的节点和)
*/
/*
int sum_tree(struct TreeNode* root){
if(!root) return 0;
return sum_tree(root->left) + sum_tree(root->right) + root->val;
}
void post_order(struct TreeNode* root, int *slope){
if(!root) return;
int l = sum_tree(root->left);
int r = sum_tree(root->right);
post_order(root->left, slope);
post_order(root->right, slope);
*slope += abs(l - r);
}
*/
/*改进思路,将每次遍历的左右节点之和存起来*/
int post_order(struct TreeNode* root, int *slope){
if(!root) return 0;
int l = post_order(root->left, slope);
int r = post_order(root->right, slope);
*slope += abs(l - r);
return l + r + root->val;
}
int findTilt(struct TreeNode* root){
int slope = 0;
post_order(root, &slope);
return slope;
}