Skip to content

Commit 1197452

Browse files
authored
Create README.md
1 parent 9b86c73 commit 1197452

File tree

1 file changed

+182
-0
lines changed
  • 17 - Binary Tree Data Structure Problems/05 - Diameter of Binary Tree

1 file changed

+182
-0
lines changed
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
<h1 align='center'>Diameter - of - Binary - Tree</h1>
2+
3+
## Problem Statement
4+
5+
**Problem URL :** [Diameter of Binary Tree](https://leetcode.com/problems/diameter-of-binary-tree/)
6+
7+
![image](https://github.com/user-attachments/assets/1bf407d7-02a2-46b4-a3bb-928e7c7c0f71)
8+
9+
## Problem Explanation
10+
The goal of this problem is to find the **diameter** of a binary tree.
11+
12+
The diameter (or width) of a binary tree is defined as the **length of the longest path** between any two nodes in the tree. This path does not necessarily pass through the root node, and it is measured by the number of edges between nodes.
13+
14+
#### Examples:
15+
1. **Example 1**:
16+
```
17+
1
18+
/ \
19+
2 3
20+
/ \
21+
4 5
22+
```
23+
- The longest path is from node `4` to node `5` through node `2`, and it includes three edges (4 → 2 → 1 → 3).
24+
- The diameter here is `3`.
25+
26+
2. **Example 2**:
27+
```
28+
1
29+
/
30+
2
31+
/
32+
3
33+
```
34+
- The longest path is from node `3` to node `1`, which contains two edges.
35+
- The diameter here is `2`.
36+
37+
3. **Example 3**:
38+
- For an empty tree (`root == NULL`), the diameter is `0`.
39+
40+
### Step 2: Approach to Solve the Problem
41+
42+
#### Beginner-Friendly Thinking Process:
43+
44+
1. **Recursive Traversal for Longest Path Calculation**:
45+
- We can approach this problem by recursively finding the longest path for each node’s left and right subtrees.
46+
- At each node, we calculate three potential longest paths:
47+
- Diameter of the left subtree.
48+
- Diameter of the right subtree.
49+
- Path that passes through the node, calculated as the depth of the left subtree + depth of the right subtree + 1 (for the current node).
50+
51+
2. **Combine Results to Find the Maximum Diameter**:
52+
- For each node, take the maximum of these three options (left diameter, right diameter, path through node) and update our answer if this maximum is larger than the current maximum diameter.
53+
54+
3. **Recursive Steps**:
55+
- Traverse to the left and right children to get their respective diameters and depths.
56+
- Calculate the possible longest path using the node’s children.
57+
- Return the maximum diameter encountered so far, as well as the depth of the subtree rooted at the current node.
58+
59+
## Problem Solution
60+
```cpp
61+
/**
62+
* Definition for a binary tree node.
63+
* struct TreeNode {
64+
* int val;
65+
* TreeNode *left;
66+
* TreeNode *right;
67+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
68+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
69+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
70+
* };
71+
*/
72+
class Solution {
73+
public:
74+
pair<int, int> diameter(TreeNode* root){
75+
if(root == NULL){
76+
return {0, 0};
77+
}
78+
79+
pair<int, int> left = diameter(root -> left);
80+
pair<int, int> right = diameter(root -> right);
81+
82+
int op1 = left.first;
83+
int op2 = right.first;
84+
int op3 = left.second + right.second + 1;
85+
86+
pair<int, int> ans;
87+
ans.first = max(op1, max(op2, op3));
88+
ans.second = max(left.second, right.second) + 1;
89+
90+
return ans;
91+
}
92+
int diameterOfBinaryTree(TreeNode* root) {
93+
return diameter(root).first - 1;
94+
}
95+
};
96+
```
97+
98+
## Problem Solution Explanation
99+
100+
```cpp
101+
class Solution {
102+
public:
103+
pair<int, int> diameter(TreeNode* root){
104+
if(root == NULL){
105+
return {0, 0};
106+
}
107+
```
108+
- **Explanation**: If `root` is `NULL`, we return `{0, 0}`, where `0` represents both the diameter and depth. For an empty tree, the diameter is `0`.
109+
110+
```cpp
111+
pair<int, int> left = diameter(root -> left);
112+
pair<int, int> right = diameter(root -> right);
113+
```
114+
- **Explanation**: Recursively calculate the diameter and depth for the left and right subtrees. Each subtree will return a `pair<int, int>`, where `first` is the diameter and `second` is the depth.
115+
116+
```cpp
117+
int op1 = left.first;
118+
int op2 = right.first;
119+
int op3 = left.second + right.second + 1;
120+
```
121+
- **Explanation**:
122+
- `op1` is the diameter of the left subtree.
123+
- `op2` is the diameter of the right subtree.
124+
- `op3` is the diameter if the path passes through the current node, calculated as the depth of the left subtree + depth of the right subtree + 1 for the current node.
125+
126+
```cpp
127+
pair<int, int> ans;
128+
ans.first = max(op1, max(op2, op3));
129+
ans.second = max(left.second, right.second) + 1;
130+
```
131+
- **Explanation**: `ans.first` stores the maximum diameter from the options `op1`, `op2`, and `op3`.
132+
- `ans.second` stores the depth of the subtree rooted at `root`, calculated as `1 + max(left.second, right.second)`.
133+
134+
```cpp
135+
return ans;
136+
}
137+
```
138+
- **Explanation**: Return the `pair` containing the maximum diameter and depth for the current subtree.
139+
140+
```cpp
141+
int diameterOfBinaryTree(TreeNode* root) {
142+
return diameter(root).first - 1;
143+
}
144+
};
145+
```
146+
- **Explanation**: `diameter(root).first` provides the diameter of the tree in terms of nodes, so we subtract `1` to convert it to edges, as required by the problem.
147+
148+
### Step-by-Step Example Walkthrough
149+
150+
Consider the following binary tree:
151+
152+
```
153+
1
154+
/ \
155+
2 3
156+
/ \
157+
4 5
158+
```
159+
160+
1. **Recursive Calculations**:
161+
- For each node, calculate the diameter and depth of both left and right subtrees.
162+
2. **Node 4 and Node 5**:
163+
- Both are leaf nodes, so the depth is `1` and the diameter is `0`.
164+
3. **Node 2**:
165+
- Left subtree (node `4`) has a depth of `1`, diameter of `0`.
166+
- Right subtree (node `5`) has a depth of `1`, diameter of `0`.
167+
- Diameter at node `2` is `max(0, 0, 1 + 1 + 1) = 3`.
168+
- Depth at node `2` is `1 + max(1, 1) = 2`.
169+
4. **Node 3**:
170+
- It has no children, so the depth is `1` and the diameter is `0`.
171+
5. **Node 1**:
172+
- Left subtree (node `2`) has a depth of `2`, diameter of `3`.
173+
- Right subtree (node `3`) has a depth of `1`, diameter of `0`.
174+
- Diameter at node `1` is `max(3, 0, 2 + 1 + 1) = 3`.
175+
- Depth at node `1` is `1 + max(2, 1) = 3`.
176+
177+
The overall diameter of the tree is `3`, so the function returns `3 - 1 = 2`.
178+
179+
### Step 4: Time and Space Complexity
180+
181+
1. **Time Complexity**: **O(N)**, where `N` is the number of nodes in the tree. Each node is visited once, so the time complexity grows linearly with the size of the tree.
182+
2. **Space Complexity**: **O(H)**, where `H` is the height of the tree. This space is required for the recursive call stack. In the worst case (skewed tree), it could be `N`, while in a balanced tree, it’s `log(N)`.

0 commit comments

Comments
 (0)