欢迎关注我的leetcode习题解答集,不断完善中,希望可以带给你帮助,共同进步
leetcode习题解答集
题意理解:以[1,2,3,4,null,5]为例,在计算点1的倾斜度时,不是3-2=1,而应该是1的左子树的全部之和减去1的右子树的全部之和,即3+5-(2+4)=2,然后加上2的倾斜度4,3的倾斜度5,也就是11
开始的时候是这么写的(错误的):
class Solution(object):
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
sum = 0
if root:
sum += self.findTilt(root.left)
sum += self.findTilt(root.right)
if root.left != None and root.right != None:
sum += abs((root.left.val-root.right.val))
else:
if root.left == None and root.right != None:
sum += root.right.val
if root.right == None and root.left != None:
sum += root.left.val
else:
pass
return sum
else:
return 0
- 正确做法
class Solution(object):
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.ans = 0
def _sum(node):
if not node:
return 0
else:
left = _sum(node.left)
right = _sum(node.right)
self.ans+= abs(left-right)
return node.val+left+right
_sum(root)
return self.ans