Given the root of a binary tree, return the sum of every tree node’s tilt.
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 nodes have a tilt of 0.
The tilt of the whole tree is the sum of the tilts of all its nodes.
To solve this problem, we’ll use a Depth-First Search (DFS) approach, which will allow us to calculate both the sum of the nodes’ values and the tilt in a single pass. We’ll perform the following steps recursively:
Here is the Python program that implements the 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: 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)
node_tilt = abs(left_sum - right_sum)
total_tilt += node_tilt
return node.val + left_sum + right_sum
dfs(root)
return total_tilt
The time complexity of the above solution is O(n), where n is the number of nodes in the binary tree. This is because we visit each node exactly once.
The space complexity is O(h), where h is the height of the tree. This is due to the recursion stack space utilization. In the worst case, for a skewed binary tree, h could be equal to n, but for a balanced binary tree, h = log(n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?