LeetCode 543: Diameter of Binary Tree Solution
Master LeetCode problem 543 (Diameter of Binary Tree), 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.
543. Diameter of Binary Tree
Problem Explanation
Explanation
To find the diameter of a binary tree, we need to calculate the maximum path length between any two nodes in the tree. This path may or may not pass through the root. We can solve this problem by recursively traversing the tree and calculating the height of each node. The diameter passing through a node is the sum of the heights of its left and right subtrees. We need to keep track of the maximum diameter found during the traversal.
- Recursively calculate the height of each node in the tree.
- For each node, calculate the diameter passing through that node as the sum of the heights of its left and right subtrees.
- Keep track of the maximum diameter found during the traversal.
- Return the maximum diameter as the result.
Time Complexity: O(n) where n is the number of nodes in the tree. Space Complexity: O(h) where h is the height of the tree.
Solution Code
class Solution {
int maxDiameter = 0;
public int diameterOfBinaryTree(TreeNode root) {
calculateHeight(root);
return maxDiameter;
}
private int calculateHeight(TreeNode node) {
if (node == null) {
return 0;
}
int leftHeight = calculateHeight(node.left);
int rightHeight = calculateHeight(node.right);
maxDiameter = Math.max(maxDiameter, leftHeight + rightHeight);
return 1 + Math.max(leftHeight, rightHeight);
}
}
Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 543 (Diameter of Binary Tree)?
This page provides optimized solutions for LeetCode problem 543 (Diameter of Binary Tree) 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 543 (Diameter of Binary Tree)?
The time complexity for LeetCode 543 (Diameter of Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 543 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 543 in Java, C++, or Python.