Leetcode 671. Second Minimum Node In a Binary Tree

本文详细解析了LeetCode上的第671题“二叉树中第二小的节点值”,介绍了题目要求和两种解题思路:使用set存储节点值并查找第二小值,以及递归遍历树并维护两个变量记录最小值和第二小值。

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);
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值