563. 二叉树的坡度

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;
    }
}
相关推荐
m0_5474866611 小时前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr17 小时前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_317 小时前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
金融小师妹17 小时前
AI金融能力评估:18个主流模型金融问题平均错误率达57%
人工智能·云计算·逻辑回归·深度优先
All for pursuit.17 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.18 小时前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣18 小时前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.99221 小时前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
淡海水1 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1011 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质