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;
    }
}
相关推荐
踢足球09291 小时前
寒假打卡:2026-01-24
数据结构·算法
tobias.b3 小时前
408真题解析-2010-9-数据结构-折半查找的比较次数
java·数据结构·算法·计算机考研·408真题解析
im_AMBER3 小时前
Leetcode 105 K 个一组翻转链表
数据结构·学习·算法·leetcode·链表
sin_hielo3 小时前
leetcode 1877
数据结构·算法·leetcode
睡不醒的kun3 小时前
定长滑动窗口-基础篇(2)
数据结构·c++·算法·leetcode·职场和发展·滑动窗口·定长滑动窗口
txzrxz4 小时前
单调栈详解(含题目)
数据结构·c++·算法·前缀和·单调栈
程序员-King.4 小时前
day167—递归—二叉树的直径(LeetCode-543)
算法·leetcode·深度优先·递归
jiaguangqingpanda5 小时前
Day28-20260124
java·数据结构·算法
风筝在晴天搁浅6 小时前
hot100 543.二叉树的直径
算法·深度优先
程序员-King.6 小时前
day168—递归—二叉树的最大路径和(LeetCode-124)
算法·leetcode·深度优先·递归