563. Binary Tree Tilt
题目描述
给定一个二叉树,计算它的tilt。每个节点的tilt是它左子树节点之和与右子树节点之和的差的绝对值。null视为0,示例如下。
Input:
1
/ \
2 3
Output: 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1
思路历程
//要用深度优先遍历
//并不是两个孩子比较这么简单,而是所有左子树之和与右子树之和进行比较
//进行中序遍历??
//随便什么顺序遍历都可以吗??
优化过程
1、最开始以为只是简单地比较两个孩子
int findTilt(TreeNode* root) {
/*
if( !root ) return 0;
else{
if( root->left != 0 && root->right != 0 )
{
int a = root->left->val;
int b = root->right->val;
int tilt = a - b > 0 ? (a - b):(b - a);
return tilt + findTilt(root->left) + findTilt(root->right);
}
else if ( root->left != 0 )
return root->left->val + findTilt(root->left);
else if ( root->right != 0 )
return root->right->val + findTilt(root->right);
else
return 0;
*/
}
2、要比较两个子树的值之差,必须保存子树和。
int findTilt(TreeNode* root) {
int sum = 0;
int tilt = 0;
postorder(root,tilt,sum);
return tilt;
}
/*
int postorder(TreeNode* node, int& tilt, int& sum){
//s代表以node为根节点的树节点之和,tilt代表node的左右子树差的绝对值
if( !node ) return 0;
int a = postorder(node->left,tilt,sum);
int b = postorder(node->right,tilt,sum);
tilt += a - b > 0 ? (a - b):(b - a);
sum = node->val + a + b;
return sum;
//postorder(node->left,tilt,sum); //发现这两行是多余的,因为在计算和的过程中,已经运行过一遍,tilt的值已经修改
//postorder(node->right,tilt,sum);
}*/
3、而子树和可以通过函数返回实现,没必要作为引用一直传递。
class Solution {
public:
int findTilt(TreeNode* root) {
int tilt = 0;
postorder(root,tilt);
return tilt;
}
//改进版
int postorder(TreeNode* node, int& tilt){
if( !node ) return 0;
int a = postorder(node->left,tilt);
int b = postorder(node->right,tilt);
tilt += a - b > 0 ? (a - b):(b - a);
return node->val + a + b;
}
};
总结
其实AC的过程中自己还有点迷糊,不过这是第一次自己写的代码跟discuss里面投票支持的代码思路、表达都近乎一致,虽然是一个easy的题目,但是还是很欣慰,不由得想记录下来以勉励自己继续加油。