Golang | Leetcode Golang题解之第563题二叉树的坡度

题目:

题解:

Go 复制代码
func findTilt(root *TreeNode) (ans int) {
    var dfs func(*TreeNode) int
    dfs = func(node *TreeNode) int {
        if node == nil {
            return 0
        }
        sumLeft := dfs(node.Left)
        sumRight := dfs(node.Right)
        ans += abs(sumLeft - sumRight)
        return sumLeft + sumRight + node.Val
    }
    dfs(root)
    return
}

func abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}
相关推荐
不知名XL2 小时前
day50 单调栈
数据结构·算法·leetcode
@––––––2 小时前
力扣hot100—系列2-多维动态规划
算法·leetcode·动态规划
YuTaoShao3 小时前
【LeetCode 每日一题】1653. 使字符串平衡的最少删除次数——(解法三)DP 空间优化
算法·leetcode·职场和发展
cpp_25014 小时前
P10570 [JRKSJ R8] 网球
数据结构·c++·算法·题解
cpp_25014 小时前
P8377 [PFOI Round1] 暴龙的火锅
数据结构·c++·算法·题解·洛谷
TracyCoder1234 小时前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表
cpp_25014 小时前
P9586 「MXOI Round 2」游戏
数据结构·c++·算法·题解·洛谷
望舒5136 小时前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode
铉铉这波能秀6 小时前
LeetCode Hot100数据结构背景知识之集合(Set)Python2026新版
数据结构·python·算法·leetcode·哈希算法
参.商.6 小时前
【Day 27】121.买卖股票的最佳时机 122.买卖股票的最佳时机II
leetcode·golang