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;
    }
}
相关推荐
垆边人似月.1 小时前
移动长度 k 子串使字符串变成回文
数据结构·算法
David猪大卫1 小时前
【C++修炼】string类:string类的模拟实现
c语言·开发语言·数据结构·c++·经验分享·笔记·学习
jeo陽2 小时前
05-数组与冒泡排序:第一个数据结构与经典算法
c语言·数据结构·算法
Nil2083 小时前
leetcode 75颜色分类
数据结构·算法·leetcode
小poop3 小时前
高级排序算法与性能对比——归并、非比较排序及总结
数据结构·算法·排序算法
用户84913717547164 小时前
Redis 跳表用了"随机"的魔法,实现了比平衡树更快的查找!
数据结构·redis
不会就选b4 小时前
算法日常・每日刷题--<动态规划>29
数据结构·算法·leetcode
垆边人似月.4 小时前
最少的元素个数使和为 target
数据结构·c++·算法
彧azz5 小时前
B-树学习总结:从结构特性到核心操作的系统复习
数据结构·笔记·b树·学习
All for pursuit.15 小时前
【动态规划-21】312.戳气球
数据结构·c++·算法·leetcode·动态规划