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;
    }
}
相关推荐
Yhame.6 分钟前
【使用层次序列构建二叉树(数据结构C)】
c语言·开发语言·数据结构
雾月5530 分钟前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展
Pasregret1 小时前
访问者模式:分离数据结构与操作的设计模式
数据结构·设计模式·访问者模式
阿让啊2 小时前
C语言中操作字节的某一位
c语言·开发语言·数据结构·单片机·算法
草莓啵啵~3 小时前
搜索二叉树-key的搜索模型
数据结构·c++
丶Darling.4 小时前
26考研 | 王道 | 数据结构 | 第八章 排序
数据结构·考研·排序算法
我也不曾来过14 小时前
list底层原理
数据结构·c++·list
mit6.8246 小时前
[贪心_7] 最优除法 | 跳跃游戏 II | 加油站
数据结构·算法·leetcode
keep intensify6 小时前
通讯录完善版本(详细讲解+源码)
c语言·开发语言·数据结构·算法
shix .6 小时前
2025年PTA天梯赛正式赛 | 算法竞赛,题目详解
数据结构·算法