Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

day 25 q2 solution in python and cpp #623

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions Day-25/Q2: Convert BST to Greater Tree/Tech-neophyte--pc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
## Approach 1: Using stack
## Python code:
```
class Solution:
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
stack, summ, node = [], 0, root
while stack or node:
while node:
stack.append(node)
node = node.right
node = stack.pop()
node.val += summ
summ = node.val
node = node.left
return root
```
## Approach 2: using recursive dfs
## python code:
```
def dfs(node, val):
if node.right:
val = dfs(node.right, val)
val += node.val
node.val = val
if node.left:
val = dfs(node.left, val)
return val
dfs(root, 0)
return root
```
## Approach
This C++ code defines a `Solution` class with a method `convertBST` that takes the root of a binary search tree (BST) and returns the same tree modified to be a Greater Tree. The `convertToGT` function recursively traverses the BST in reverse in-order, updating node values to the sum of greater values encountered so far. The final modified tree is returned.
## cpp Code
```
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* convertToGT(TreeNode* root,int& sum){
if(!root)return NULL;
convertToGT(root->right,sum);
sum+=root->val;
root->val=sum;
convertToGT(root->left,sum);
return root;
}
TreeNode* convertBST(TreeNode* root) {
int sum=0;
return convertToGT(root,sum);
}

};
```