#include<fstream>
#include<sstream>
#include<vector>
#include<unordered_set>
#include<time.h>
#include<stdio.h>
using namespace std;
struct BTNode {
int val;
BTNode *left;
BTNode *right;
BTNode(int x) : val(x), left(NULL), right(NULL) {}
};
int computeAmp(vector<int> &path){
int min= INT_MAX, max=INT_MIN;
for(int i=0;i<path.size();++i){
if(min> path[i]){
min = path[i];
}
if(max < path[i]){
max = path[i];
}
}
return abs(max-min);
}
int returnMax(vector<int> &res){
int max=INT_MIN;
for(int i=0;i< res.size();++i){
if(max < res[i]){
max = res[i];
}
}
return max;
}
void maxAmpHelp(BTNode *root, vector<int> &path, vector<int> &res){
if(!root->left && !root->right){
path.push_back(root->val);
int v = computeAmp(path);
res.push_back(v);
}
else{
path.push_back(root->val);
if(root->left){
maxAmpHelp(root->left,path,res);
path.pop_back();
}
if(root->right){
maxAmpHelp(root->right,path,res);
path.pop_back();
}
}
return;
}
int maxAmplitude (BTNode *root){
vector<int> res, path;
maxAmpHelp(root, path, res);
int maxAmp = returnMax(res);
return maxAmp;
}
int main(){
BTNode *root = new BTNode (1);
root->left = new BTNode (2);
root->right = new BTNode (6);
root->left->left = new BTNode (10);
root->left->right = new BTNode (-22);
root->right->left = new BTNode (-36);
root->right->right = new BTNode (8);
root->left->left->left = new BTNode(5);
root->left->right->right = new BTNode(56);
int max = maxAmplitude(root); //output == 78
cout<<endl<<"Max Amplitude is:"<< max <<endl;
getchar();
return 0;
}
No comments:
Post a Comment