LeetCode 563: Binary Tree Tilt
Problem Description
Explanation
To solve this problem, we can perform a post-order traversal of the binary tree. At each node, we calculate the sum of values in its left subtree and right subtree recursively. Then, we calculate the tilt for the current node and add it to a global variable storing the total tilt. Finally, we return the total tilt.
Algorithm:
- Define a global variable
totalTilt
to store the total tilt of the tree. - Implement a post-order traversal function that calculates the sum of values in left and right subtrees, calculates the tilt at the current node, and updates the
totalTilt
. - Return the
totalTilt
after traversing the entire tree.
Time Complexity:
The time complexity of this algorithm is O(n), where n is the number of nodes in the binary tree.
Space Complexity:
The space complexity of this algorithm is O(h), where h is the height of the binary tree.
Solutions
class Solution {
int totalTilt = 0;
public int findTilt(TreeNode root) {
calculateTilt(root);
return totalTilt;
}
private int calculateTilt(TreeNode node) {
if (node == null) {
return 0;
}
int leftSum = calculateTilt(node.left);
int rightSum = calculateTilt(node.right);
totalTilt += Math.abs(leftSum - rightSum);
return leftSum + rightSum + node.val;
}
}
Related LeetCode Problems
Loading editor...