呓语Beta 2.0 首页 镜头后 灶台前 捐赠者名单 有趣的小站

leetcode 563 Binary Tree Tile

文档信息

leetcode 563 Binary Tree Tile

解法一

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def findTilt(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        
        sum_left = self.findTilt(root.left)
        sum_right = self.findTilt(root.right)
        
        left = root.left.val if root.left else 0
        right = root.right.val if root.right else 0
                
        root.val = root.val + left + right
        
        return abs(left - right) + sum_left + sum_right

note

捐赠支持

可以使用支付宝转帐给richard.ma.19850509#gmail.com(请将#替换为@),谢谢!

Fork me on GitHub