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

Day22 q2: Sum of Left Leaves #464 , Day18 q1: max difference between Node and Ancestor . #578

Merged
merged 2 commits into from
Jan 27, 2024
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* 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:
int maxAncestorDiff(TreeNode* root) {
int m = 0;
dfs(root, m);
return m;
}

private:
std::pair<int, int> dfs(TreeNode* root, int& m) {
if (root == nullptr) {
return {INT_MAX, INT_MIN};
}

auto left = dfs(root->left, m);
auto right = dfs(root->right, m);

int minVal = std::min(root->val, std::min(left.first, right.first));
int maxVal = std::max(root->val, std::max(left.second, right.second));

m = std::max({m, std::abs(minVal - root->val), std::abs(maxVal - root->val)});

return {minVal, maxVal};
}
};
31 changes: 31 additions & 0 deletions Day-22/q2: Sum of Left Leaves/Akansha--C.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* 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 {
void solve(TreeNode*root,int &sum,int &flag){
if(root==NULL)return ;
if(root->left==NULL && root->right==NULL &&flag==1){
sum+=root->val;
}
flag=1;
solve(root->left,sum,flag);
flag=0;
solve(root->right,sum,flag);

}
public:
int sumOfLeftLeaves(TreeNode* root) {
int sum=0;
int flag=0;
solve(root,sum,flag);
return sum;
}
};