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;
    }
}
相关推荐
老师我太想进步了202610 小时前
【数据结构-12】树与二叉树的结构、概念
数据结构
2601_9679801114 小时前
Python中heapq模块的各种用法实例
数据结构·python·算法·应用实例·heapq模块
zaizai100715 小时前
算法(左程云)2
数据结构
漂流瓶jz16 小时前
UVA-1615 高速公路 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·贪心算法·贪心·aoapc·算法竞赛入门经典·uva
夊16 小时前
数据结构第四课:栈与队列
数据结构
凌冰_1 天前
数据结构 - 时间空间复杂度(一)
数据结构·算法·软件工程
郝学胜-神的一滴1 天前
Effective Python 条款36:优雅拼装迭代器与生成器
开发语言·数据结构·人工智能·python·numpy·scikit-learn
console.log('npc')2 天前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
郝学胜-神的一滴2 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
FR02EN7773 天前
[LeetCode] 26、80.删除有序数组中的重复项 题解
数据结构·算法