跳过正文
  1. leetcode 题解/

563_二叉树的坡度

·64 字·1 分钟

类型:树

    1. 二叉树的坡度 💚

    https://leetcode-cn.com/problems/binary-tree-tilt/

    ❓ 给定一个二叉树,计算 整个树 的坡度 。

    节点的坡度:左子树的节点之和与右子树节点之和的差的绝对值 。

    树的坡度:所有节点的坡度之和。

    💡 后序遍历

    class Solution:
        def __init__(self):
            self.ans = 0
    
        def findTilt(self, root: TreeNode) -> int:
            # 典型的后序遍历题
            if not root:
                return 0
    
            def dfs(node):
                if not node:
                    return 0
    
                leftSum = dfs(node.left)
                rightSum = dfs(node.right)
    
                tilt = abs(leftSum - rightSum)
                self.ans += tilt
    
                return leftSum + node.val + rightSum
    
            dfs(root)
            return self.ans