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;
    }
}
相关推荐
多米Domi01117 小时前
0x3f第33天复习 (16;45-18:00)
数据结构·python·算法·leetcode·链表
曹仙逸18 小时前
数据结构day04
数据结构
Lips61118 小时前
2026.1.16力扣刷题
数据结构·算法·leetcode
曹仙逸18 小时前
数据结构day05
数据结构
睡一觉就好了。19 小时前
树的基本结构
数据结构
kaikaile199519 小时前
A星算法避开障碍物寻找最优路径(MATLAB实现)
数据结构·算法·matlab
今天_也很困19 小时前
LeetCode 热题100-15.三数之和
数据结构·算法·leetcode
思成Codes21 小时前
ACM训练:接雨水3.0——动态接雨水
数据结构·算法
sin_hielo21 小时前
leetcode 2943
数据结构·算法·leetcode
Snow_day.1 天前
有关平衡树
数据结构·算法·贪心算法·动态规划·图论