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;
    }
}
相关推荐
pursuit_csdn3 小时前
LeetCode 1022. Sum of Root To Leaf Binary Numbers
算法·leetcode·深度优先
散峰而望6 小时前
C++ 启程:从历史到实战,揭开命名空间的神秘面纱
c语言·开发语言·数据结构·c++·算法·github·visual studio
仟濹7 小时前
【算法打卡day10(2026-02-24 周二)复习算法:DFS BFS 并查集】
算法·深度优先·图论·dfs·bfs·广度优先·宽度优先
Darkwanderor7 小时前
数据结构 - 并查集的应用
数据结构·c++·并查集
菜鸡儿齐8 小时前
leetcode-全排列
算法·leetcode·深度优先
Hag_209 小时前
LeetCode Hot100 53.最大子数组和
数据结构·算法·leetcode
王老师青少年编程9 小时前
csp信奥赛C++之反素数
数据结构·c++·数学·算法·csp·信奥赛·反素数
元亓亓亓12 小时前
考研408--数据结构--day17--外部排序
数据结构·考研
仰泳的熊猫13 小时前
蓝桥杯算法提高VIP-种树
数据结构·c++·算法·蓝桥杯·深度优先·图论
郝学胜-神的一滴14 小时前
FastAPI:Python 高性能 Web 框架的优雅之选
开发语言·前端·数据结构·python·算法·fastapi