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     }
  • 相关阅读:
    获取浏览器类型和版本
    js 防抖、节流
    判断数据类型
    一个函数判断数据类型
    面试题3道
    如何处理循环的异步操作
    this的原理以及几种使用场景
    v-model原理解析
    小程序setData数据量过大时候会对渲染有影响吗?
    js中in关键字的使用方法
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7707939.html
Copyright © 2011-2022 走看看