树的坡度计算
题目
题解
我的题解:双重递归(开销极大)
存在冗余遍历
class Solution {
public int findTilt(TreeNode root) {
if (root == null) {
return 0;
}
return findTilt(root.left) + findTilt(root.right) + Math.abs(dfs(root.right) - dfs(root.left));
}
public int dfs(TreeNode root) {
if (root == null) {
return 0;
}
return dfs(root.right) + dfs(root.left) + root.val;
}
}
官方题解
正好利用递归中的左右的和,不存在冗余遍历。
class Solution {
int tilt=0;
public int findTilt(TreeNode root) {
traverse(root);
return tilt;
}
public int traverse(TreeNode root)
{
if(root==null )
return 0;
int left=traverse(root.left);
int right=traverse(root.right);
tilt+=Math.abs(left-right);
return left+right+root.val;
}
}