Second Minimum Node In a Binary Tree:求二叉树第二小的值
来源:互联网 发布:天猫淘宝优惠卷代理 编辑:程序博客网 时间:2024/05/19 23:05
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 7Output: 5Explanation: The smallest value is 2, the second smallest value is 5.
Example 2:
Input: 2 / \ 2 2Output: -1Explanation: The smallest value is 2, but there isn't any second smallest value.思路:保存所有节点的值,找出第二小,时空复杂度均为O(n)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { public void dfs(TreeNode n,Set<Integer> set){ if(n==null) return; set.add(n.val); dfs(n.left,set); dfs(n.right,set); } public int findSecondMinimumValue(TreeNode root) { Set<Integer> set = new HashSet<Integer>(); dfs(root,set); int min1 = root.val; int ans = Integer.MAX_VALUE; for (int v : set) { if (min1 < v && v < ans) ans = v; } return ans < Integer.MAX_VALUE ? (int) ans : -1; }}
阅读全文
0 0
- Second Minimum Node In a Binary Tree:求二叉树第二小的值
- leetcode 671. Second Minimum Node In a Binary Tree 第二小数字 + 深度优先遍历DFS
- 671. Second Minimum Node In a Binary Tree
- leetcode 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- leetcode 671. Second Minimum Node In a Binary Tree
- Second Minimum Node In a Binary Tree问题及解法
- leetcode 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- Leetcode671. Second Minimum Node In a Binary Tree
- LeetCode 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- 671. Second Minimum Node In a Binary Tree
- [LeetCode] Second Minimum Node In a Binary Tree
- LeetCode#671 Second Minimum Node In a Binary Tree (week13)
- 671. Second Minimum Node In a Binary Tree
- Java学习4:方法的重载(Overload)详解及实例说明
- linux 设置mysql 数据库编码utf8
- c语言头文件的作用以及写法
- Linux--shell寻找命令的顺序
- 334. Increasing Triplet Subsequence
- Second Minimum Node In a Binary Tree:求二叉树第二小的值
- imageview
- 计算机中的颜色如何表示?
- maven使用antrun运行不同版本的插件
- leetcode: 46. Permutations
- 32-多线程(wait和sleep的区别)1 2 33-多线程(停止线程方式-定义标记) 35-多线程(守护线程-setDaemon).1 2
- 40行JavaScript代码实现的3D旋转魔方动画效果
- 作业
- Cookie与Session机制