Skip to content

Commit a6171d6

Browse files
authored
Merge pull request codeharborhub#1703 from Damini2004/GFG-0102
Added GFG 0102-Minimum-BST-Sum-Subtree.md
2 parents b78a55c + 3b7574d commit a6171d6

File tree

1 file changed

+211
-0
lines changed

1 file changed

+211
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,211 @@
1+
---
2+
id: minimum-bst-sum-subtree
3+
title: Minimum-BST-Sum-Subtree (Geeks for Geeks)
4+
sidebar_label: Minimum BST Sum Subtree
5+
tags:
6+
- Intermediate
7+
- Geeks for Geeks
8+
- CPP
9+
- Python
10+
- DSA
11+
description: "This is a solution to the Minimum BST Sum Subtree problem on Geeks for Geeks."
12+
---
13+
## Problem Description
14+
Every house in the colony has at most one pipe going into it and at most one pipe going out of it. Tanks and taps are to be installed in a manner such that every house with one outgoing pipe but no incoming pipe gets a tank installed on its roof and every house with only an incoming pipe and no outgoing pipe gets a tap.
15+
Given two integers n and p denoting the number of houses and the number of pipes. The connections of pipe among the houses contain three input values: a_i, b_i, d_i denoting the pipe of diameter d_i from house a_i to house b_i, find out the efficient solution for the network.
16+
The output will contain the number of pairs of tanks and taps t installed in first line and the next t lines contain three integers: house number of tank, house number of tap and the minimum diameter of pipe between them.
17+
18+
## Examples
19+
**Example 1:**
20+
**Input:**
21+
```
22+
5
23+
/ \
24+
4 6
25+
/ \
26+
3 7
27+
/
28+
1
29+
```
30+
**Output:** 1
31+
**Example 2:**
32+
**Input:**
33+
```
34+
9
35+
\
36+
10
37+
\
38+
11
39+
```
40+
**Output:** 9
41+
## Your Task
42+
The task is to complete the function minValue() which takes root as the argument and returns the minimum element of BST. If the tree is empty, there is no minimum element, so return -1 in that case.
43+
Expected Time Complexity: $O(Height of the BST)$
44+
Expected Auxiliary Space: $O(1)$.
45+
## Constraints
46+
- `0 <= n <= 10^4`
47+
48+
49+
## Your Task
50+
The task is to complete the function minValue() which takes root as the argument and returns the minimum element of BST. If the tree is empty, there is no minimum element, so return -1 in that case.
51+
52+
Expected Time Complexity: $O(Height of the BST)$
53+
Expected Auxiliary Space: $O(1)$.
54+
55+
## Constraints
56+
57+
- `0 <= n <= 10^4`
58+
59+
## Problem Explanation
60+
61+
The "Smallest Subtree with all the Deepest Nodes" is a problem where given a binary tree, you need to find the smallest subtree that contains all the deepest nodes. Let's break down the problem step-by-step:
62+
63+
**Problem Statement**
64+
You are given a binary tree.
65+
Your task is to find the smallest subtree that contains all the deepest nodes in the original tree.
66+
**Key Points**
67+
Deepest Nodes: Nodes that are at the maximum depth from the root of the tree.
68+
Smallest Subtree: Among all subtrees containing these deepest nodes, the one with the smallest number of nodes.
69+
70+
### Code Implementation
71+
<Tabs>
72+
<TabItem value="Python" label="Python" default>
73+
<SolutionAuthor name="@ngmuraqrdd"/>
74+
```python
75+
class Solution:
76+
def lca(self, root, p, q):
77+
if root in (None, p, q): return root
78+
l = self.lca(root.left, p, q)
79+
r = self.lca(root.right, p, q)
80+
return root if l and r else l or r
81+
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
82+
a = []
83+
def dfs(node, h):
84+
if not node:
85+
return
86+
if len(a) == h:
87+
a.append([])
88+
a[h].append(node)
89+
dfs(node.left, h+1)
90+
dfs(node.right, h+1)
91+
dfs(root, 0)
92+
p, q = a[-1][0], a[-1][-1]
93+
return self.lca(root, p, q)
94+
```
95+
</TabItem>
96+
<TabItem value="C++" label="C++" default>
97+
<SolutionAuthor name="@ngmuraqrdd"/>
98+
```cpp
99+
class Solution {
100+
public:
101+
TreeNode* subtreeWithAllDeepest(TreeNode* root) {
102+
vector<TreeNode*> temp;
103+
vector<vector<TreeNode*>> level;
104+
unordered_map<TreeNode*,TreeNode*> hash;
105+
queue<pair<TreeNode*,TreeNode*>> q;
106+
q.push({root,NULL});
107+
q.push({NULL,NULL});
108+
hash[root] = NULL;
109+
while (!q.empty())
110+
{
111+
auto [node,parent] = q.front();q.pop();
112+
if (node == NULL)
113+
{
114+
level.push_back(temp);
115+
temp.clear();
116+
if (q.size()>0)
117+
{
118+
q.push({NULL,NULL});
119+
}
120+
}
121+
else
122+
{
123+
temp.push_back(node);
124+
hash[node] = parent;
125+
if (node->left)
126+
{
127+
q.push({node->left,node});
128+
}
129+
if (node->right)
130+
{
131+
q.push({node->right,node});
132+
}
133+
}
134+
}
135+
temp = level.back();
136+
queue<TreeNode*> qe;
137+
unordered_map<TreeNode*,int> vis;
138+
for (auto leaves : temp)
139+
{
140+
vis[leaves] = 1;
141+
qe.push(leaves);
142+
}
143+
while (!qe.empty())
144+
{
145+
int sz = qe.size();
146+
if (sz == 1)
147+
{
148+
return qe.front();
149+
}
150+
while (sz--)
151+
{
152+
auto node = qe.front();qe.pop();
153+
154+
while (sz--)
155+
{
156+
auto node = qe.front();qe.pop();
157+
auto parent = hash[node];
158+
if (vis.find(parent) == vis.end())
159+
{
160+
vis[parent] = 1;
161+
qe.push(parent);
162+
}
163+
}
164+
}
165+
return NULL;
166+
}
167+
};
168+
```
169+
</TabItem>
170+
</Tabs>
171+
172+
173+
## Solution Logic
174+
**DFS to Collect Nodes by Depth:**
175+
- You initialize an empty list a to store nodes at each depth.
176+
- The dfs function is called with the root node and depth 0.
177+
- For each node, if the current depth h matches the length of a, it means you have reached a new depth level, so you append an empty list to a.
178+
- The node is then added to the appropriate sublist corresponding to its depth.
179+
- The function is recursively called for left and right children, incrementing the depth by 1 for each recursive call.
180+
**Finding the LCA:**
181+
- After collecting all nodes, p and q are set to the first and last nodes in the deepest level sublist (a[-1]).
182+
- The lca function is a recursive function that finds the lowest common ancestor of p and q.
183+
- If the current node root is None, p, or q, it returns root.
184+
- Otherwise, it recursively calls lca on the left and right children.
185+
- If both recursive calls return non-None values, it means p and q are found in different subtrees, and thus the current node root is their LCA.
186+
- If only one side returns a non-None value, it means both p and q are in the same subtree, so the LCA is in that subtree.
187+
## Time Complexity
188+
$O(Height of the BST)$
189+
## Space Complexity
190+
Expected Auxiliary Space: $O(1)$.
191+
## Resources
192+
- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/find-the-minimum-element-in-a-binary-search-tree/)
193+
- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/)
194+
- **Author's Geeks for Geeks Profile:** | [DaminiChachane](https://leetcode.com/u/divcxl15/) |
195+
This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow.
196+
197+
## Time Complexity
198+
$O(Height of the BST)$
199+
200+
## Space Complexity
201+
202+
Expected Auxiliary Space: $O(1)$.
203+
204+
## Resources
205+
206+
- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/find-the-minimum-element-in-a-binary-search-tree/)
207+
- **LeetCode Problem:** [LeetCode Problem](https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/)
208+
- **Author's Geeks for Geeks Profile:** | [DaminiChachane](https://leetcode.com/u/divcxl15/) |
209+
210+
This format ensures that all necessary details about the problem and its solution are clearly presented and easy to follow.
211+

0 commit comments

Comments
 (0)