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;
    }
}
相关推荐
fpcc20 小时前
数据结构—表
数据结构
Funing721 小时前
FreeRTOS学习day1:Keil 工程配置与 FreeRTOS 链表机制理解
数据结构·学习·链表
utf8mb4安全女神1 天前
【Redis数据库】哨兵集群/redis集群/安装配置/主从复制/数据持久化操作/数据结构/安全限制/PHP redis/
linux·服务器·数据结构·数据库·redis·缓存
丘山望岳1 天前
哈希——数据分类存储柜
数据结构·散列表
山峰哥1 天前
数据库工程:Explain执行计划对比实战指南‌
数据库·sql·oracle·深度优先·宽度优先
WL学习笔记1 天前
链式队列(数据结构)
前端·数据结构·jquery
人道领域1 天前
【LeetCode刷题日记】贪心算法理论与实战:455.分发饼干最优解
java·开发语言·数据结构·算法·leetcode·贪心算法
小巧的蜡烛1 天前
对CSS中的Position、Float属性的一些深入探讨
数据结构·mysql
疋瓞2 天前
python和C++对比(1)_数据类型和数据结构
数据结构·c++·python
如此这般英俊2 天前
手搓Claude Code-第六章 subagent
数据结构·人工智能·python·语言模型·自然语言处理