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# 发送邮件笔记(一)
    windows API(一)
    SubSonic3.0安装
    Node.js安装MongoDB驱动
    JDBC连接数据库方法
    Delphi LiveBindings如何绑定一个对象(二)(转)
    delphi RTTI机制学习(一)
    Delphi LiveBinds组件
    mysql 每个分类各取5条
    mysql in(...) 1次取出当前记录及上1条下1条记录, 且使用了主键作为索引
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7707939.html
Copyright © 2011-2022 走看看