563. Binary Tree Tilt

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

class Solution:
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return self.tilt(root)+self.findTilt(root.left)+self.findTilt(root.right)


def tilt(self,roo):
if not roo.right and not roo.left:
return 0
if not roo.right and roo.left:
return roo.left.val
if not roo.left and roo.right:
return roo.right.val
else:
return abs(roo.left.val-roo.right.val)

自己写的代码,理解题目意思出了问题,应该是左子树的和减去右子树的和

class Solution:
    def findTilt(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.ans=0
        def sumnode(roo):
            if not roo:return 0
            left,right=sumnode(roo.left),sumnode(roo.right)
            self.ans+=abs(left-right)
            return roo.val+left+right
        sumnode(root)
        return self.ans

  

Runtime: 104 ms, faster than 68.09% of Python3 online submissions forBinary Tree Tilt.

class Solution:
    def findTilt(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        tilt = [0]
        generate(root,tilt)
        return tilt[0]
        
def generate(node,tilt) :
    
    if not node :
        return 0 
    else :
        L = generate(node.left,tilt) 
        R = generate(node.right,tilt)
        
        tilt[0] += abs(L-R)
        
        return L + R + node.val

  

原文地址:https://www.cnblogs.com/captain-dl/p/10297524.html