题目:
Given a binary tree, return the tilt of the whole tree.
The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.
The tilt of the whole tree is defined as the sum of all nodes’ tilt.
Example:
Input:
1
/ \
2 3
Output: 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1
题目分析:这个题目是求树的倾度,树的倾度是每个节点倾度的和,但每个节点倾度的计算相对而言是独立的,需要统计各子树的节点和,在这题中犯的错误是没有读清题目,然后并不了解倾度的概念,然后就做题目,有点断章取义了。
python代码的实现
class Solution(object):
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
if root.left == None and root.right == None:
return 0
if root.left == None:
return abs(self.subtree(root.right)) + self.findTilt(root.right)
if root.right == None:
return abs(self.subtree(root.left)) + self.findTilt(root.left)
return abs(self.subtree(root.left) - self.subtree(root.right)) + self.findTilt(root.left) + self.findTilt(root.right)
def subtree(self, root):
if root == None:
return 0
return root.val + self.subtree(root.left) + self.subtree(root.right)
重新读题之后,重新书写本题目,又有了新的不同的见解和写法
class Solution(object):
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
return abs(self.subtree_sum(root.left)-self.subtree_sum(root.right)) + self.findTilt(root.left) + self.findTilt(root.right)
def subtree_sum(self, root):
if root:
return root.val + self.subtree_sum(root.left) + self.subtree_sum(root.right)
return 0
大佬们的代码:
def findTilt(self, root):
self.ans = 0
def _sum(node):
if not node: return 0
left, right = _sum(node.left), _sum(node.right)
self.ans += abs(left - right)
return node.val + left + right
_sum(root)
return self.ans
学到了一个新的写法:
可以将判断root is None,来写为not root,这样更简洁,专业。
利用了一个全局变量,类变量来实现计数,然后遍历树的节点,然后得其左右子树的数值之和。
def findTilt(self, root):
def tilt(root):
# return (sum, tilt) of tree
if not root: return (0, 0)
left = tilt(root.left)
right = tilt(root.right)
return (left[0] + right[0] + root.val, abs(left[0] - right[0]) + left[1] + right[1])
return tilt(root)[1]
这个 大佬的想法,是另辟蹊径,我还是好好看一下大佬的代码,然后好好学习一波。这个第一个表述的当前节点的倾斜度,第二个表述的是累计的情况。