Skip to content

Commit

Permalink
Merge pull request #578 from Akansha77/Akansha_75
Browse files Browse the repository at this point in the history
Day22 q2: Sum of Left Leaves #464 , Day18 q1: max difference between Node and Ancestor .
  • Loading branch information
kratika-Jangid authored Jan 27, 2024
2 parents 16ffb26 + 4660a83 commit 013ee00
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
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;
}
};

0 comments on commit 013ee00

Please sign in to comment.