思路
通过题意可以知道根节点一定是最小值,但次大值有很多可能,如果左右节点的值都比根节点大,那次大值是其中最小值;
但如果有子节点和根节点相同,则在两边都可能出现。
普通的想法就是层序遍历,找出其中严格大于最小值中的最小值,即为整棵树的次小值
class Solution {
public:
int findSecondMinimumValue(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
int ans = -1;
int minest = root->val;
while(!q.empty()) {
int num = q.size();
while(num--) {
TreeNode* tmp = q.front();
q.pop();
int x = 0, y = 0;
if(tmp->left != nullptr) {
x = tmp->left->val;
q.push(tmp->left);
if(x > minest && (ans == -1 || x < ans) ) ans = x;
}
if(tmp->right != nullptr) {
y = tmp->right->val;
q.push(tmp->right);
if(y > minest && (ans == -1 || y < ans) ) ans = y;
}
}
}
return ans;
}
};
但层序遍历没有充分利用该树的性质,如果再该节点更新的答案,那么该节点往下的子节点中一定不会存在更好的解;
如果在该节点出更新了答案,说明该节点严格大于最小值,因为该节点是该节点子树中的最小值,所以该子树中的值都大于等于该节点,也会存在更好的次大值,也就是不会存在大于全局最小值的但比答案更小的值,所以就不需要拓展该子树,这样剪枝更快。
class Solution {
public:
int findSecondMinimumValue(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
int ans = -1;
int minest = root->val;
while(!q.empty()) {
int num = q.size();
while(num--) {
TreeNode* tmp = q.front();
q.pop();
int x = 0, y = 0;
if(tmp->left != nullptr) {
x = tmp->left->val;
if(x > minest && (ans == -1 || x < ans) ) ans = x;
else q.push(tmp->left);
}
if(tmp->right != nullptr) {
y = tmp->right->val;
if(y > minest && (ans == -1 || y < ans) ) ans = y;
else q.push(tmp->right);
}
}
}
return ans;
}
};