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 }
分类:
leetcode_tree
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!