Skip to content

Instantly share code, notes, and snippets.

@joe-cai
Last active September 18, 2016 01:07
Show Gist options
  • Save joe-cai/55dfe040d4c3f01012a6 to your computer and use it in GitHub Desktop.
Save joe-cai/55dfe040d4c3f01012a6 to your computer and use it in GitHub Desktop.
Maximal Amplitude of a Binary Tree
class TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int val_) : val(val_) {}
};
class Solution {
int ans = 0;
int maxAmp(struct TreeNode* root) {
if (root == NULL) return 0;
helper(root, root->val, root->val);
return ans;
}
void helper(struct TreeNode* root, int min_val, int max_val) {
if (root == NULL) return 0;
min_val = min(min_val, root->val);
max_val = max(max_val, root->val);
ans = max(ans, max_val - min_val);
helper(root->left, min_val, max_val);
helper(root->right, min_val, max_val);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment