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;
    }
}
相关推荐
程序员老舅4 小时前
啃透 I2C 驱动开发,才算入门嵌入式 Linux 内核驱动
数据结构·驱动开发·b树·内核·嵌入式·嵌入式开发·i2c
青山木12 小时前
Hot 100 --- 搜索插入位置
java·数据结构·算法·leetcode
Livia要学习15 小时前
Python2和Python3字典底层原理
数据结构
青梅橘子皮15 小时前
STL---map/set... “家族“详解(从使用到底层)(1)
数据结构·算法
Adios79416 小时前
搜索二维矩阵 II
java·数据结构·算法
木井巳18 小时前
【DFS解决floodfill算法】岛屿的最大面积
java·算法·leetcode·深度优先
Tisfy18 小时前
LeetCode 1406.石子游戏 III:递归(DFS+记忆化) / 递推(DP+原地滚动)
leetcode·游戏·深度优先·dfs·题解·博弈
灵枢时代20 小时前
小程序在生鲜配送行业,如何设计夜间预约和次日达的订单处理流程?
数据结构·人工智能·小程序
一条大祥脚20 小时前
ABC468 扫描线|贡献法|二阶差分|线段树优化DP
数据结构·算法
mifengxing2 天前
LeetCode 189 轮转数组|3种解法拆解,从暴力到O(1)原地最优解
数据结构·算法·leetcode