개발공부/algorithm

[Leetcode][python] 563. Binary Tree Tilt - DFS

so.py 2021. 5. 16. 21:00

  • Leetcode 563. Binary Tree Tilt
  • Level: easy
  • Link
 

Binary Tree Tilt - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

My Approach

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

class Solution:
    def findTilt(self, root: TreeNode) -> int:
        total_tilt = 0
        
        def dfs(node):
            nonlocal total_tilt
            
            if not node:
                return 0
            
            left_sum = dfs(node.left)
            right_sum = dfs(node.right)
            tilt = abs(left_sum - right_sum)
            total_tilt += tilt
            
            return left_sum + right_sum + node.val
        
        dfs(root)
        return total_tilt