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;
    }
}
相关推荐
benjormin24 分钟前
Java数据结构 二叉搜索树
数据结构·算法
H.莓飛4 小时前
【数据结构】排序总结与规模实测
linux·服务器·开发语言·数据结构·visual studio·1024程序员节
码少女5 小时前
数据结构——B+树基础
数据结构·b树
揽星河..7 小时前
【初阶数据结构】常见的排序算法
数据结构·排序算法·1024程序员节
YLCHUP8 小时前
【模拟&STL】题解:AT_abc203_e [ABC203E] White Pawn_基础算法_数据结构_STL模板库_AtcoderABC_C++算法竞赛
数据结构·c++·算法·leetcode·动态规划·哈希算法·近邻算法
啊啊啊啊啊!!!!8 小时前
【c++】⽤哈希表封装myunordered_map和myunordered_set
数据结构·哈希算法·散列表
(●—●)橘子……8 小时前
力扣 第525场周赛 练习理解
数据结构·python·学习·算法·leetcode
Tt有了t8 小时前
Redis的数据结构
数据结构·数据库·redis
東隅已逝,桑榆非晚8 小时前
map和set的使用
数据结构·c++·笔记·学习
2601_970703838 小时前
除湿机原理研究报告:一台机器在物理上能走多远
大数据·数据结构·算法·数据库架构·推荐算法