每日一题:671. 二叉树中第二小的节点

解题思路

层序遍历树,然后将所有节点排序,取出第二个即为第二最小值

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int findSecondMinimumValue(TreeNode root) {
        LinkedList<TreeNode> tree = new LinkedList<>();
        if(root==null){
            return -1;
        }
        tree.add(root);
        Set<Integer> set = new HashSet<>();
        List<Integer> list = new ArrayList<>();
        while(!tree.isEmpty()){
            int n = tree.size();
            for(int i=0;i<n;i++){
                TreeNode node = tree.getFirst();
                if(!set.contains(node.val)){
                    set.add(node.val);
                    list.add(node.val);
                }
                tree.removeFirst();
                if(node.left!=null){
                    tree.add(node.left);
                }
                if(node.right!=null){
                    tree.add(node.right);
                }
            }
        }
        Collections.sort(list);
        int min = list.get(0);
        for(int i=0;i<list.size();i++){
            if(list.get(i)>min){
                min = list.get(i);
                return min;
            }
        }
        return -1;
    }
}
上一篇:LeetCode-671. 二叉树中第二小的节点


下一篇:Codeforces Round #671 (Div. 2) (A - B题)