这题用二叉树中序遍历想到了,坡度扔一个列表里面最后求和也想到了,没想到的是返回值是啥,很接近.......
# 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
"""
self.tiles = []
self.getNodeTilt(root)
return sum(self.tiles)
def getNodeTilt(self, node):
if not node:
return 0
lSum = self.getNodeTilt(node.left)
rSum = self.getNodeTilt(node.right)
self.tiles.append(abs(lSum - rSum))
return node.val + lSum + rSum
网友评论