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;
    }
}
相关推荐
黎雁·泠崖19 小时前
栈与队列之队列入门攻略:从核心概念到链表实现
c语言·数据结构·链表
上海锟联科技19 小时前
DAS-U1000 极致版解调卡
数据结构·算法·嵌入式实时数据库
Watermelo61719 小时前
TOON:一种为大模型设计的JSON压缩型数据结构
数据结构·人工智能·语言模型·自然语言处理·数据挖掘·数据分析·json
聆风吟º1 天前
【数据结构手札】空间复杂度详解:概念 | 习题
java·数据结构·算法
not coder1 天前
树形结构,从零到工业级评论系统
数据结构
smj2302_796826521 天前
解决leetcode第3801题合并有序列表的最小成本
数据结构·python·算法·leetcode
sinat_255487811 天前
InputStream/OutputStream小讲堂
java·数据结构·算法
副露のmagic1 天前
更弱智的算法学习 day16
数据结构·学习·算法
Love Song残响1 天前
30字高效MATLAB优化指南
数据结构·算法
sin_hielo1 天前
leetcode 1975
数据结构·算法·leetcode