• 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     }
  • 相关阅读:
    《互联网时代》第三集·能量
    《互联网时代》第二集·浪潮
    java 基础类库之 SysFun
    java 基础类库之 SQLFun
    java 基础类库之 FormatFun
    Java 之 JDBC
    WepE
    MySql学习笔记
    Oracle学习笔记——点滴汇总
    Linux学习笔记——基于鸟哥的Linux私房菜
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7707939.html
Copyright © 2020-2023  润新知