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;
    }
}
相关推荐
一条大祥脚16 小时前
26.1.9 轮廓线dp 状压最短路 构造
数据结构·c++·算法
cpp_250118 小时前
P2708 硬币翻转
数据结构·c++·算法·题解·洛谷
程序猿阿伟18 小时前
《Python复杂结构静态分析秘籍:递归类型注解的深度实践指南》
java·数据结构·算法
UIUI19 小时前
list_for_each_entry
linux·数据结构·链表
豆沙沙包?1 天前
2026年--Lc334-2130. 链表最大孪生和(链表转数组)--java版
java·数据结构·链表
Python_Study20251 天前
制造业数据采集系统选型指南:从技术挑战到架构实践
大数据·网络·数据结构·人工智能·架构
SmoothSailingT1 天前
408每日一题——数据结构
数据结构·考研·408
im_AMBER1 天前
Leetcode 99 删除排序链表中的重复元素 | 合并两个链表
数据结构·笔记·学习·算法·leetcode·链表
s砚山s1 天前
代码随想录刷题——二叉树篇(十三)
数据结构·算法
ulias2121 天前
AVL树的实现
开发语言·数据结构·c++·windows