563.二叉树的坡度

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

一、后序

计算左右子树之和的差,考虑后序遍历。在遍历中计算本节点坡度并修改,用一个全局变量累加坡度,并向上层返回本子树节点和

class Solution:
    def findTilt(self, root: TreeNode) -> int:
        self.res = 0

        def postOrder(root):
            if not root:
                return 0
            left = postOrder(root.left)
            right = postOrder(root.right)
            sum = left + right + root.val
            root.val = abs(left-right)
            self.res += root.val	#累加坡度
            return sum

        postOrder(root)
        return self.res

最后更新于