zoukankan      html  css  js  c++  java
  • 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.

    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.
    题目含义:一棵非空的二叉树,每一个节点的值是它的两个子节点中较小的那个值。求该二叉树中第二小的数。如果不存在则输出-1 
     1     private Set<Integer> treeSet = new TreeSet<>();
     2     private void parserTreeNode(TreeNode root)
     3     {
     4         if (root == null)return;
     5         treeSet.add(root.val);
     6         parserTreeNode(root.left);
     7         parserTreeNode(root.right);
     8     }    
     9     
    10     public int findSecondMinimumValue(TreeNode root) {
    11         parserTreeNode(root);
    12         Iterator<Integer> iterator = treeSet.iterator();
    13         int i=0;
    14         while (iterator.hasNext())
    15         {
    16             i++;
    17             int result = iterator.next();
    18             if (i==2) return result;
    19         }
    20         return -1;        
    21     }
  • 相关阅读:
    C语言I博客作业07
    C语言I博客作业06
    C语言I博客作业05
    C语言I博客作业04
    C语言I博客作业02
    Django连接MySql数据库
    asyncio异步编程
    Django-rest framework框架
    Git版本管理工具详细教程
    MySQL的sql_mode模式说明及设置
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7707939.html
Copyright © 2011-2022 走看看