Leetcode 563. Binary Tree Tilt
Given the root of a binary tree, return the tilt of the whole tree.
The tilt of a tree node is the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. The tilt of the whole tree is defined as the sum of all nodes’ tilt.
n
in the tree is reasonably small (e.g., n <= 10,000
).The main idea is to traverse the tree in a post-order manner (i.e., process children before the node itself), compute the tilt for each node, and accumulate these tilts for the final result. Post-order traversal ensures that when computing the tilt for a particular node, you have already computed the values of its children.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public class Solution {
private int totalTilt = 0;
public int findTilt(TreeNode root) {
computeTilt(root);
return totalTilt;
}
private int computeTilt(TreeNode node) {
if (node == null) {
return 0;
}
int leftSum = computeTilt(node.left);
int rightSum = computeTilt(node.right);
int nodeTilt = Math.abs(leftSum - rightSum);
totalTilt += nodeTilt;
return node.val + leftSum + rightSum;
}
public static void main(String[] args) {
TreeNode node3 = new TreeNode(3);
TreeNode node5 = new TreeNode(5);
TreeNode node2 = new TreeNode(2, node3, node5);
TreeNode node4 = new TreeNode(4);
TreeNode root = new TreeNode(1, node2, node4);
Solution solution = new Solution();
System.out.println(solution.findTilt(root)); // Output the tilt of the whole tree
}
}
O(n)
, where n
is the number of nodes in the tree. This is because each node is visited exactly once during the traversal.O(h)
, where h
is the height of the tree. This is due to the space required by the call stack during recursion. In the worst case (for a skewed tree), this could be O(n)
.This approach efficiently computes the tilt of the binary tree within the given constraints.
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?