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;
    }
}
相关推荐
神威难绷泪1 小时前
数据结构:哈希表 算法相关 排序算法
数据结构
zander2582 小时前
LeetCode 198. 打家劫舍
算法·leetcode·深度优先
Zguigo3 小时前
树的前序|中序|后序遍历【使用栈实现】
数据结构·算法
2401_869769593 小时前
list 2
数据结构·list
ambition202426 小时前
操作系统同步:读者-写者问题与读写公平法详解(附每个 PV 操作含义)
linux·开发语言·数据结构·unix
疯狂打码的少年16 小时前
【数据结构】图的存储结构:邻接矩阵与邻接表
数据结构·笔记
203号居民16 小时前
LeetCode hot 100 —41. 缺失的第一个正数
数据结构·算法·leetcode
2401_8628808220 小时前
数据结构 --- 栈
c语言·数据结构·算法
linux-hzh21 小时前
百日算法修炼 · Day 12
算法·深度优先
额额额对了1 天前
数据结构:二叉树
c语言·数据结构·算法