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;
    }
}
相关推荐
Jasmine_llq34 分钟前
《P5663 [CSP-J 2019] 加工零件》
数据结构·算法·bfs·广度优先搜索·分层 bfs /·奇偶分层最短路·奇数最短步数
stolentime1 小时前
AT_arc182_a [ARC182A] Chmax Rush!题解
数据结构·c++·算法·动态规划
写后端的胖头鱼9 小时前
一文详解B+树原理(附场景+示例)
数据结构·b树
All for pursuit.12 小时前
【位运算-1】338.比特位计数
数据结构·c++·算法·leetcode
xxwl58514 小时前
数据结构知识点和代码实现总结(C语言实现)
c语言·开发语言·数据结构
mokongJ19 小时前
17 份异构销售数据的合并清洗方案:30 万行处理耗时 9.64 秒
数据结构
蛋蛋的就会顺顺的20 小时前
hot100——二叉树
java·数据结构·算法·leetcode·力扣
List<String> error_P1 天前
freertos数据结构--链表
数据结构·链表
longlongzihan1 天前
LeetCode 128. 最长连续序列 —— 从排序到哈希集合
数据结构·c++·算法·leetcode·排序算法·哈希表
mmmmath_31 天前
二叉树の一些知识
数据结构·算法