바이너리 트리 루트 노드를 받고, 조상 노드와 자손 노드 간의 가장 큰 값 차를 구하는 문제
/**
* 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:
void SearchDFS(TreeNode *root, int &min, int &max, int &result)
{
if (root == NULL)
{
return;
}
int tempMin = std::min(root->val, min);
int tempMax = std::max(root->val, max);
result = std::max(result, abs(tempMax - tempMin));
SearchDFS(root->left, tempMin, tempMax, result);
SearchDFS(root->right, tempMin, tempMax, result);
return;
}
int maxAncestorDiff(TreeNode* root) {
int max{numeric_limits<int>::min()};
int min{numeric_limits<int>::max()};
int result{numeric_limits<int>::min()};
SearchDFS(root, min, max, result);
return result;
}
};