leetcode刷题.530. 二叉搜索树的最小绝对差.每日打卡
程序员文章站
2022-04-24 16:28:48
...
class Solution {
public:
int threeMin(int a, int b, int c) {
return (a > b) ? ((b > c) ? c : b) : ((a > c) ? c : a);
}
int maxTreeNode(TreeNode *root) {
while(nullptr != root->right)
root = root->right;
return root->val;
}
int minTreeNode(TreeNode *root) {
while(nullptr != root->left)
root = root->left;
return root->val;
}
int getMinimumDifference(TreeNode* root) {
int min_av = INT_MAX;
stack<TreeNode *> mystack;
mystack.push(root);
while(mystack.size()) {
TreeNode *node = mystack.top();
mystack.pop();
int r = INT_MAX, l = INT_MAX;
if(nullptr != node->right) {
mystack.push(node->right);
r = abs(minTreeNode(node->right) - node->val);
}
if(nullptr != node->left) {
mystack.push(node->left);
l = abs(maxTreeNode(node->left) - node->val);
}
min_av = threeMin(min_av, r, l);
}
return min_av;
}
};
推荐阅读