LeetCode 563: Binary Tree Tilt Solution
Master LeetCode problem 563 (Binary Tree Tilt), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
563. Binary Tree Tilt
Problem Explanation
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
totalTiltto 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
totalTiltafter 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.
Solution Code
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;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 563 (Binary Tree Tilt)?
This page provides optimized solutions for LeetCode problem 563 (Binary Tree Tilt) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 563 (Binary Tree Tilt)?
The time complexity for LeetCode 563 (Binary Tree Tilt) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 563 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 563 in Java, C++, or Python.