Skip to content

Latest commit

 

History

History
85 lines (49 loc) · 1.64 KB

0563._Binary_Tree_Tilt.md

File metadata and controls

85 lines (49 loc) · 1.64 KB

563. Binary Tree Tilt

难度: Easy

刷题内容

原题连接

内容描述


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
Note:

The sum of node values in any subtree won't exceed the range of 32-bit integer.
All the tilt values won't exceed the range of 32-bit integer.

解题方案

思路 1 - 时间复杂度: O(N)- 空间复杂度: O(1)******

写一个sums函数,input为node,返回这个node本身的value和它所有孩子的value之和,该node的tilt就是左孩子sums和右孩子sums的差值的绝对值

然后对于root和其所有子孙,只需要把他们的tilt全部加起来就是结果

beats 98.70%

class Solution(object):
    def findTilt(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.res = 0
        def sums(node):
            if not node:
                return 0
            left_sum = sums(node.left)
            right_sum = sums(node.right)
            self.res += abs(left_sum-right_sum)
            return left_sum + right_sum + node.val
        
        sums(root)
        return self.res