zoukankan      html  css  js  c++  java
  • LeetCode 671. Second Minimum Node In a Binary Tree二叉树中第二小的节点 (C++)

    题目:

    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.

    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.

    Example 1:

    Input: 
        2
       / 
      2   5
         / 
        5   7
    
    Output: 5
    Explanation: The smallest value is 2, the second smallest value is 5.
    

    Example 2:

    Input: 
        2
       / 
      2   2
    
    Output: -1
    Explanation: The smallest value is 2, but there isn't any second smallest value.

    分析:

    给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 2 或 0。如果一个节点有两个子节点的话,那么这个节点的值不大于它的子节点的值。 

    给出这样的一个二叉树,你需要输出所有节点中的第二小的值。如果第二小的值不存在的话,输出 -1 。

    首先想到可以遍历树,将节点值存进一个set中,最后返回set中第二小的值,如果只有一个元素就返回-1。

    不过题中的二叉树是特殊的,每个节点的子节点数量只能为2或0,且这个节点的值不大于它的子节点的值。基于这个特点,我们可以不使用set。遍历每个节点的时候判断当前节点是否大于等于第二小的值,因为题中的二叉树的特点,节点的子节点是大于等于当前节点的,我没就没有必要在去访问后面的节点了。

    程序:

    //use set
    class Solution {
    public:
        int findSecondMinimumValue(TreeNode* root) {
            findmin(root);
            set<int>::iterator it = s.begin();
            if (s.size() > 1)
                return *(++it);
            else
                return -1;
    
        }
        void findmin(TreeNode* root){
            if(root == nullptr) return;
            s.insert(root->val);
            findmin(root->left);
            findmin(root->right);
        }
    private:
        set<int> s;
    };
    //no set
    class Solution {
    public:
        int findSecondMinimumValue(TreeNode* root) {
            finds(root);
            if(smin != LONG_MAX) return (int)smin;
            else return -1;
        }
        void finds(TreeNode* root){
            if(root == nullptr) return;
            if(smin <= root->val) return;
            if(root->val < fmin){
                fmin = root->val;
            }
            else if(root->val < smin && root->val > fmin){
                smin = root->val;
            }
            finds(root->left);
            finds(root->right); 
        }
    private:
        long fmin = LONG_MAX;
        long smin = LONG_MAX;
    };
  • 相关阅读:
    IOS GameCenter验证登陆
    BZOJ 1597: [Usaco2008 Mar]土地购买 斜率优化
    Hihocoder #1602 : 本质不同的回文子串的数量 manacher + BKDRhash
    HDU 5343 MZL's Circle Zhou 后缀自动机+DP
    HDU 6208 The Dominator of Strings 后缀自动机
    SPOJ SUBLEX
    SPOJ LCS2
    .NET平台技术体系梳理+初学者学习路径推荐+我们的愿景与目标
    扑克模拟,牌型判断java版
    一道综合练习题实践list及dictionary集合类
  • 原文地址:https://www.cnblogs.com/silentteller/p/10903447.html
Copyright © 2011-2022 走看看