Binary Tree Tilt — LeetCode 563 Python Solution
- Problem
- #563
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given the root of a binary tree, return the sum of every tree node's tilt. The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values.
Example
- Input
- root = [1,2,3]
- Output
- 1
- Explanation
- Tilt of node 2 : |0-0| = 0 (no children)
Python solution
# 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: Optional[TreeNode]) -> int:
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
l, r = dfs(root.left), dfs(root.right)
nonlocal ans
ans += abs(l - r)
return l + r + root.val
ans = 0
dfs(root)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the number of nodes auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 563. Binary Tree Tilt is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 563. Binary Tree Tilt?
- LeetCode 563. Binary Tree Tilt is rated Easy on LeetCode.
- What is the time complexity of LeetCode 563. Binary Tree Tilt?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 563. Binary Tree Tilt?
- The Python solution on this page uses O(n), where n is the number of nodes auxiliary space.
- What topics does LeetCode 563. Binary Tree Tilt cover?
- LeetCode 563. Binary Tree Tilt is tagged Tree, Depth-First Search and Binary Tree on LeetCode.