|
| 1 | +--- |
| 2 | +id: diameter-of-a-binary-tree |
| 3 | +title: Diameter of Binary tree |
| 4 | +sidebar_label: 0543. Diameter of Binary tree |
| 5 | + |
| 6 | +tags: |
| 7 | +- Binary Tree |
| 8 | +- Diameter |
| 9 | + |
| 10 | +description: "This is a solution to the Diameter of Binary tree problem on LeetCode." |
| 11 | +--- |
| 12 | + |
| 13 | +## Problem Description |
| 14 | +Given the `root` of a binary tree, return *the length of the diameter of the tree*. |
| 15 | +The **diameter** of a binary tree is the **length** of the longest path between any two nodes in a tree. This path may or may not pass through the `root`. |
| 16 | +The **length** of a path between two nodes is represented by the number of edges between them. |
| 17 | +### Examples |
| 18 | + |
| 19 | +**Example 1:** |
| 20 | + |
| 21 | + |
| 22 | +``` |
| 23 | +Input: root = [1,2,3,4,5] |
| 24 | +Output: 3 |
| 25 | +Explanataion: 3 is the length of the path [4,2,1,3] or [5,2,1,3]. |
| 26 | +``` |
| 27 | + |
| 28 | +**Example 2:** |
| 29 | + |
| 30 | +``` |
| 31 | +Input: root = [1,2] |
| 32 | +Output: 1 |
| 33 | +``` |
| 34 | + |
| 35 | + |
| 36 | +### Constraints |
| 37 | +- The number of nodes in the tree is in the range `[1, 10^4]`. |
| 38 | +- `-100 <= Node.val <= 100` |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | +## Solution for Diameter of Binary tree |
| 43 | +### Approach |
| 44 | +#### Brute Force |
| 45 | +- **Define a Helper Function**: |
| 46 | + - Create a function to calculate the height of a tree. |
| 47 | +- **Calculate Diameter**: |
| 48 | + - For each node, calculate the diameter passing through that node. |
| 49 | + - The diameter passing through a node is the sum of the heights of its left and right subtrees. |
| 50 | + - Compare this diameter with the global maximum diameter. |
| 51 | +- **Traverse Tree**: |
| 52 | + - Perform a traversal of the tree (e.g., in-order, pre-order) to compute the diameter for each node. |
| 53 | + |
| 54 | +**Implementation:** |
| 55 | +```cpp |
| 56 | +#include <bits/stdc++.h> |
| 57 | +using namespace std; |
| 58 | + |
| 59 | +struct TreeNode { |
| 60 | + int val; |
| 61 | + TreeNode *left; |
| 62 | + TreeNode *right; |
| 63 | + TreeNode(int x) : val(x), left(NULL), right(NULL) {} |
| 64 | +}; |
| 65 | + |
| 66 | +int height(TreeNode* node) { |
| 67 | + if (node == NULL) { |
| 68 | + return 0; |
| 69 | + } |
| 70 | + return 1 + max(height(node->left), height(node->right)); |
| 71 | +} |
| 72 | + |
| 73 | +int diameterOfBinaryTree(TreeNode* root) { |
| 74 | + if (root == NULL) { |
| 75 | + return 0; |
| 76 | + } |
| 77 | + |
| 78 | + // Get the height of left and right sub-trees |
| 79 | + int left_height = height(root->left); |
| 80 | + int right_height = height(root->right); |
| 81 | + |
| 82 | + // Get the diameter of left and right sub-trees |
| 83 | + int left_diameter = diameterOfBinaryTree(root->left); |
| 84 | + int right_diameter = diameterOfBinaryTree(root->right); |
| 85 | + |
| 86 | + // Calculate diameter passing through the root |
| 87 | + return max(left_height + right_height, max(left_diameter, right_diameter)); |
| 88 | +} |
| 89 | + |
| 90 | +int main() { |
| 91 | + TreeNode* root = new TreeNode(1); |
| 92 | + root->left = new TreeNode(2); |
| 93 | + root->right = new TreeNode(3); |
| 94 | + root->left->left = new TreeNode(4); |
| 95 | + root->left->right = new TreeNode(5); |
| 96 | + |
| 97 | + cout << "Diameter of the binary tree is: " << diameterOfBinaryTree(root) << endl; |
| 98 | + |
| 99 | + return 0; |
| 100 | +} |
| 101 | +``` |
| 102 | +
|
| 103 | +**Complexity:** |
| 104 | +- Time Complexity: `O(n^2)` because for each node, we are calculating the height which takes O(n) time. |
| 105 | +- Space Complexity: `O(n)` due to the recursion stack. |
| 106 | +
|
| 107 | +**Corner Cases:** |
| 108 | +- Empty tree: Should return `0`. |
| 109 | +- Single node tree: Should return `0` as there are no edges. |
| 110 | +
|
| 111 | +#### Optimized Approach |
| 112 | +- **Define a Helper Function:**: |
| 113 | + - Create a function to calculate both the height and the diameter of the tree simultaneously. |
| 114 | +- **Single Traversal**: |
| 115 | + - Traverse the tree once, calculating the height and updating the maximum diameter at each node. |
| 116 | +
|
| 117 | +**Implementation:** |
| 118 | +
|
| 119 | +```cpp |
| 120 | +#include <bits/stdc++.h> |
| 121 | +using namespace std; |
| 122 | +
|
| 123 | +struct TreeNode { |
| 124 | + int val; |
| 125 | + TreeNode *left; |
| 126 | + TreeNode *right; |
| 127 | + TreeNode(int x) : val(x), left(NULL), right(NULL) {} |
| 128 | +}; |
| 129 | +
|
| 130 | +class Solution { |
| 131 | +public: |
| 132 | + int diameter; |
| 133 | +
|
| 134 | + int height(TreeNode* node) { |
| 135 | + if (node == NULL) { |
| 136 | + return 0; |
| 137 | + } |
| 138 | +
|
| 139 | + int left_height = height(node->left); |
| 140 | + int right_height = height(node->right); |
| 141 | +
|
| 142 | + // Update the diameter if left_height + right_height is larger |
| 143 | + diameter = max(diameter, left_height + right_height); |
| 144 | +
|
| 145 | + // Height of the current node is max of heights of left and right subtrees plus 1 |
| 146 | + return 1 + max(left_height, right_height); |
| 147 | + } |
| 148 | +
|
| 149 | + int diameterOfBinaryTree(TreeNode* root) { |
| 150 | + diameter = 0; |
| 151 | + height(root); |
| 152 | + return diameter; |
| 153 | + } |
| 154 | +}; |
| 155 | +
|
| 156 | +int main() { |
| 157 | + TreeNode* root = new TreeNode(1); |
| 158 | + root->left = new TreeNode(2); |
| 159 | + root->right = new TreeNode(3); |
| 160 | + root->left->left = new TreeNode(4); |
| 161 | + root->left->right = new TreeNode(5); |
| 162 | +
|
| 163 | + Solution solution; |
| 164 | + cout << "Diameter of the binary tree is: " << solution.diameterOfBinaryTree(root) << endl; |
| 165 | +
|
| 166 | + return 0; |
| 167 | +} |
| 168 | +``` |
| 169 | + |
| 170 | +**Complexity:** |
| 171 | +- Time Complexity: `O(n)`since we are traversing each node only once. |
| 172 | +- Space Complexity: `O(n)`due to the recursion stack. |
| 173 | + |
| 174 | +**Corner Cases:** |
| 175 | +- Empty tree: Should return `0`. |
| 176 | +- Single node tree: Should return `0` as there are no edges. |
| 177 | + |
| 178 | + |
| 179 | + ## Code in Different Languages |
| 180 | + |
| 181 | + <Tabs> |
| 182 | + |
| 183 | + <TabItem value="JavaScript" label="JavaScript"> |
| 184 | + <SolutionAuthor name="@vansh-codes" /> |
| 185 | + |
| 186 | + ```javascript |
| 187 | + var diameterOfBinaryTree = function(root) { |
| 188 | + let diameter = 0; |
| 189 | + |
| 190 | + function height(node) { |
| 191 | + if (node === null) return 0; |
| 192 | + let leftHeight = height(node.left); |
| 193 | + let rightHeight = height(node.right); |
| 194 | + |
| 195 | + // Update the diameter |
| 196 | + diameter = Math.max(diameter, leftHeight + rightHeight); |
| 197 | + |
| 198 | + return 1 + Math.max(leftHeight, rightHeight); |
| 199 | + } |
| 200 | + |
| 201 | + height(root); |
| 202 | + return diameter; |
| 203 | + }; |
| 204 | + ``` |
| 205 | + |
| 206 | + </TabItem> |
| 207 | + |
| 208 | + <TabItem value="TypeScript" label="TypeScript"> |
| 209 | + <SolutionAuthor name="@vansh-codes" /> |
| 210 | + |
| 211 | + ```typescript |
| 212 | + function diameterOfBinaryTree(root: TreeNode | null): number { |
| 213 | + let diameter = 0; |
| 214 | +
|
| 215 | + function height(node: TreeNode | null): number { |
| 216 | + if (node === null) return 0; |
| 217 | + let leftHeight = height(node.left); |
| 218 | + let rightHeight = height(node.right); |
| 219 | +
|
| 220 | + // Update the diameter |
| 221 | + diameter = Math.max(diameter, leftHeight + rightHeight); |
| 222 | +
|
| 223 | + return 1 + Math.max(leftHeight, rightHeight); |
| 224 | + } |
| 225 | +
|
| 226 | + height(root); |
| 227 | + return diameter; |
| 228 | + } |
| 229 | + ``` |
| 230 | + |
| 231 | + </TabItem> |
| 232 | + |
| 233 | + <TabItem value="Python" label="Python"> |
| 234 | + <SolutionAuthor name="@vansh-codes" /> |
| 235 | + |
| 236 | + ```python |
| 237 | + class Solution(object): |
| 238 | + def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int: |
| 239 | + self.diameter = 0 |
| 240 | +
|
| 241 | + def height(node: TreeNode) -> int: |
| 242 | + if not node: |
| 243 | + return 0 |
| 244 | + left_height = height(node.left) |
| 245 | + right_height = height(node.right) |
| 246 | +
|
| 247 | + # Update the diameter |
| 248 | + self.diameter = max(self.diameter, left_height + right_height) |
| 249 | +
|
| 250 | + return 1 + max(left_height, right_height) |
| 251 | +
|
| 252 | + height(root) |
| 253 | + return self.diameter |
| 254 | + ``` |
| 255 | + |
| 256 | + </TabItem> |
| 257 | + |
| 258 | + <TabItem value="Java" label="Java"> |
| 259 | + <SolutionAuthor name="@vansh-codes" /> |
| 260 | + |
| 261 | + ```java |
| 262 | + import java.util.Arrays; |
| 263 | +
|
| 264 | + class Solution { |
| 265 | + private int diameter; |
| 266 | + public int diameterOfBinaryTree(TreeNode root) { |
| 267 | + diameter = 0; |
| 268 | +
|
| 269 | + height(root); |
| 270 | + return diameter; |
| 271 | + } |
| 272 | +
|
| 273 | + private int height(TreeNode node) { |
| 274 | + if (node == null) { |
| 275 | + return 0; |
| 276 | + } |
| 277 | +
|
| 278 | + int leftHeight = height(node.left); |
| 279 | + int rightHeight = height(node.right); |
| 280 | +
|
| 281 | + // Update the diameter |
| 282 | + diameter = Math.max(diameter, leftHeight + rightHeight); |
| 283 | +
|
| 284 | + return 1 + Math.max(leftHeight, rightHeight); |
| 285 | + } |
| 286 | + }; |
| 287 | + ``` |
| 288 | + |
| 289 | + </TabItem> |
| 290 | + |
| 291 | + <TabItem value="C++" label="C++"> |
| 292 | + <SolutionAuthor name="@vansh-codes" /> |
| 293 | + |
| 294 | + ```cpp |
| 295 | + class Solution { |
| 296 | + public: |
| 297 | + int diameter; |
| 298 | +
|
| 299 | + int diameterOfBinaryTree(TreeNode* root) { |
| 300 | + diameter = 0; |
| 301 | + height(root); |
| 302 | + return diameter; |
| 303 | + } |
| 304 | + private: |
| 305 | + int height(TreeNode* node) { |
| 306 | + if (node == nullptr) { |
| 307 | + return 0; |
| 308 | + } |
| 309 | +
|
| 310 | + int leftHeight = height(node->left); |
| 311 | + int rightHeight = height(node->right); |
| 312 | +
|
| 313 | + // Update the diameter |
| 314 | + diameter = max(diameter, leftHeight + rightHeight); |
| 315 | +
|
| 316 | + return 1 + max(leftHeight, rightHeight); |
| 317 | + } |
| 318 | + }; |
| 319 | + ``` |
| 320 | + |
| 321 | + </TabItem> |
| 322 | + </Tabs> |
| 323 | + |
| 324 | +## References |
| 325 | + |
| 326 | +- **LeetCode Problem**: [Diameter of Binary tree](https://leetcode.com/problems/diameter-of-binary-tree/description/) |
| 327 | + |
| 328 | +- **Solution Link**: [LeetCode Solution](https://leetcode.com/problems/diameter-of-binary-tree/solutions/) |
0 commit comments