Leetcode 671. Second Minimum Node In a Binary Tree
Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly two or zero sub-node. If the node has two sub-nodes, then this node’s value is the smaller value among its two sub-nodes. More formally, the property root.val = min(root.left.val, root.right.val) always holds.Given such a binary tree, you need to output the second minimum value in the set made of all the nodes’ value in the whole tree.If no such second minimum value exists, output -1 instead.
题目大意:
返回二叉树中第二小结点的值,规定每个结点要么没有子结点,要么有两个子结点,且父结点一定小于等于子结点,如果没有第二小的值则返回-1.
解题思路:
1.遍历所有结点并加入到set中,如果set的元素个数小于等于1则返回-1,否则返回第二个元素(set有序)。
2.暴力搜索,根结点一定为最小值,则初始话第一小first为根,第二小second为无穷大,对根结点传入first, second进行递归,如果当前结点的值不等于first则说明比first要大,再与second比较,若小于second则更新second,递归每一个结点至空返回。
代码1:
class Solution {
public:
int findSecondMinimumValue(TreeNode* root) {
if(!root)
return -1;
helper(root->left);
helper(root->right);
if(s.size() >= 2)
{
int x = *next(s.begin(), 1);
return x;
}
return -1;
}
void helper(TreeNode* root)
{
if(!root)
return;
s.insert(root->val);
helper(root->left);
helper(root->right);
}
private:
set<int> s;
};
代码2:
class Solution {
public:
int findSecondMinimumValue(TreeNode* root) {
int first = root->val, second = INT_MAX;
helper(root, first, second);
return (first == second || INT_MAX == second) ? -1 : second;
}
void helper(TreeNode* root, int &first, int &second)
{
if(!root)
return;
if(root->val != first && root->val < second)
{
second = root->val;
}
helper(root->left, first, second);
helper(root->right, first, second);
}
};
本文详细解析了LeetCode上的第671题“二叉树中第二小的节点值”,介绍了题目要求和两种解题思路:使用set存储节点值并查找第二小值,以及递归遍历树并维护两个变量记录最小值和第二小值。
402

被折叠的 条评论
为什么被折叠?



