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;
    }
}
相关推荐
Irissgwe11 分钟前
二叉树进阶,map和set
数据结构·算法
浅念-44 分钟前
C++ 异常
开发语言·数据结构·数据库·c++·经验分享·笔记·学习
handler011 小时前
基础算法:BFS
开发语言·数据结构·c++·学习·算法·宽度优先
j_xxx404_1 小时前
LeetCode模拟算法精解II:外观数列与数青蛙
数据结构·c++·算法·leetcode
这是个栗子1 小时前
前端开发中的常用工具函数(五)
javascript·数据结构·reduce
像污秽一样1 小时前
算法设计与分析-习题9.2
数据结构·算法·排序算法·dfs
Book思议-1 小时前
【数据结构实战】:基于C语言单链表实现红旗渠景区年卡信息管理系统
c语言·开发语言·数据结构
像污秽一样2 小时前
算法设计与分析-习题9.1
数据结构·算法·dfs·dp·贪婪
星空露珠2 小时前
迷你世界UGC3.0脚本Wiki生物模块管理接口 Monster
开发语言·数据结构·算法·游戏·lua
leo__5203 小时前
经典链路预测相似性算法的MATLAB实现
数据结构·算法·matlab