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;
    };
  • 相关阅读:
    打jar包的命令
    WebServiceWSDLWeb
    linux命令之检测端口是否启用
    mybatis generator 插件安装及使用
    Mybatis 中一对多,多对一的配置
    大数据时代日志分析平台ELK的搭建
    关于RestfulAPI与SpringMVC之间的传值
    linux快速清空文件内容
    Linux之第一个shell命令
    Linux之yum
  • 原文地址:https://www.cnblogs.com/silentteller/p/10903447.html
Copyright © 2011-2022 走看看