563. 二叉树的坡度
原题
java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int res = 0;
public int findTilt(TreeNode root) {
if(root==null){
return 0;
}
dfs(root);
return res;
}
public int dfs(TreeNode root){
if(root==null){
return 0;
}
//左子树遍历递归
int left = dfs(root.left);
//右子树遍历递归
int right = dfs(root.right);
//求累计坡度
res += Math.abs(left-right);
//计算当前结点和其子树的总值
return root.val+left+right;
}
}